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?
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. });
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With