Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show 404 error page after [Authorize] failure

I have an action I want to restrict only to role "Admin". I did it like this:

[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)

After manually going under Controller/Edit/1 path I'm redirected to login page. Well, that isn't bad maybe, but I want to show 404 instead of it and try to stick using attributes for it. Is that possible?

like image 800
deha Avatar asked Feb 29 '12 17:02

deha


People also ask

How to handle 404 error in c#?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred. });

How to set 404 page in ASP.NET mvc?

NotFoundMVC - Provides a user-friendly 404 page whenever a controller, action or route is not found in your ASP.NET MVC3 application. A view called NotFound is rendered instead of the default ASP.NET error page. NotFoundMvc automatically installs itself during web application start-up.

How do I redirect an error page in web config?

The <customErrors> section in Web. config has two attributes that affect what error page is shown: defaultRedirect and mode . The defaultRedirect attribute is optional. If provided, it specifies the URL of the custom error page and indicates that the custom error page should be shown instead of the Runtime Error YSOD.


1 Answers

Is that possible?

Sure, you could write a custom authorize attribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Shared/401.cshtml"
        };
    }
}

and then use it:

[MyAuthorize(Roles = "Admin")]
public ActionResult Edit(int id)

Remark: you probably want to show a 401 or 403 page if the user is not authorized instead of 404 which is for file not found.

like image 57
Darin Dimitrov Avatar answered Sep 30 '22 08:09

Darin Dimitrov