Home How to only throw a Status code when unauthorized in MVC 5 - no redirect
Reply: 0

How to only throw a Status code when unauthorized in MVC 5 - no redirect

rawk
1#
rawk Published in 2017-09-14 08:35:46Z

So I created a custom authorization filter in MVC 5 following an answer given on stackoverflow. It looks like this:

public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.Result is HttpUnauthorizedResult)
        {

            filterContext.Result = new RedirectResult("~/Account/AccessDenied");
        }
    }
}

Since I don't want to actually redirect the user to a page at all but just want to show a bootstrap alert, I customized the code like this:

public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.HttpContext.Response.StatusCode = 200;
        }
    }
}

and I use this javascript code:

$('#settingsIndex').on('click', function (e) {

    $.ajax({
        type: 'GET',
        url: '/Settings/Index',
        success: function () {
            window.location.href = "/Settings/Index";
        },
        statusCode: {
            200: function () {
                $('#loginAlert').show();
            }
        }
    });

});

This does work to a point. When I click on the link with the specified Id the alert will show but nevertheless MVC still redirects me to the login page (when only using the filterContext.HttpContext.Response.StatusCode = 200; code piece), when adding my custom redirect it redirects me to my custom page.

I would rather have it not redirect the user at all and just show the bootstrap alert.

I tried adding this piece of code also:

HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;

That doesn't work either. How can I stop MVC from redirecting and only show the alert?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.341171 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO