[英]How to redirect to a route in an ActionResult in ASP.Net MVC 3
I am trying to create an access denied ActinoResult to return from my controllers. 我正在尝试创建一个拒绝ActinoResult的访问权限从我的控制器返回。 I have the following implementation 我有以下实现
public class AccessDeniedResult : ActionResult
{
public 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. 这不起作用,因为来自HttpResponseBase的NotImplementedException作为context.HttpContext.Response传递。
How do you write a correct redirecting action result in MVC3? 你如何在MVC3中编写正确的重定向动作结果?
You should be returning HttpUnauthorizedResult like so: 你应该像这样返回HttpUnauthorizedResult:
return new HttpUnauthorizedResult();
Additionally, you should consider creating a new class deriving from AuthorizeAttribute to do security checks. 此外,您应该考虑创建一个派生自AuthorizeAttribute的新类来进行安全检查。 You can then add this directive to your web.config to control where the client is directed: 然后,您可以将此指令添加到web.config以控制客户端的定向位置:
<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: 最后,您可以添加自定义路由来控制将用户定向到〜/ 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). 也许你应该尝试继承RedirectToRouteResult(继承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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.