I am trying to create an access denied ActinoResult to return from my controllers. I have the following implementation
public class AccessDeniedResult : ActionResult
{
publi开发者_JAVA技巧c override void ExecuteResult(ControllerContext context)
{
if (null != context && null != context.HttpContext && null != context.HttpContext.Response)
{
context.HttpContext.Response.StatusCode = 401;
context.HttpContext.Response.RedirectToRoute("AccessDenied");
}
}
}
This does not work because of a NotImplementedException coming from HttpResponseBase being passed as context.HttpContext.Response.
How do you write a correct redirecting action result in MVC3?
You should be returning HttpUnauthorizedResult like so:
return new HttpUnauthorizedResult();
Additionally, you should consider creating a new class deriving from AuthorizeAttribute to do security checks. You can then add this directive to your web.config to control where the client is directed:
<customErrors mode="On" defaultRedirect="~/Home/Error">
<error statusCode="401" redirect="~/AccessDenied" />
</customErrors>
Finally, you can add a custom route to control what happens when the user is directed to ~/AccessDenied:
Route route = routes.MapRoute("AccessDeniedRoute", "AccessDenied", new { controller = "MyCustomErrorController", action = "My401Action" });
RouteTable.Routes.Add(route);
Maybe you should try inheriting from RedirectToRouteResult(which inherits ActionResult).
You can also look at the source code for that class to see how they do it:
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
if (context.IsChildAction) {
throw new InvalidOperationException(MvcResources.RedirectAction_CannotRedirectInChildAction);
}
string destinationUrl = UrlHelper.GenerateUrl(RouteName, null /* actionName */, null /* controllerName */, RouteValues, Routes, context.RequestContext, false /* includeImplicitMvcValues */);
if (String.IsNullOrEmpty(destinationUrl)) {
throw new InvalidOperationException(MvcResources.Common_NoRouteMatched);
}
context.Controller.TempData.Keep();
if (Permanent) {
context.HttpContext.Response.RedirectPermanent(destinationUrl, endResponse: false);
}
else {
context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);
}
}
精彩评论