c# - 如何在 ASP.Net MVC 3 中重定向到 ActionResult 中的路由

标签 c# asp.net asp.net-mvc asp.net-mvc-3

我正在尝试创建一个访问被拒绝的 ActinoResult 以从我的 Controller 返回。我有以下实现

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");
        }
    }
}

这不起作用,因为来自 HttpResponseBase 的 NotImplementedException 作为 context.HttpContext.Response 传递。

如何在 MVC3 中编写正确的重定向操作结果?

最佳答案

您应该像这样返回 HttpUnauthorizedResult:

return new HttpUnauthorizedResult();

此外,您应该考虑创建一个派生自 AuthorizeAttribute 的新类来进行安全检查。然后,您可以将此指令添加到您的 web.config 以控制客户端指向的位置:

<customErrors mode="On" defaultRedirect="~/Home/Error">
    <error statusCode="401" redirect="~/AccessDenied" />
</customErrors>

最后,您可以添加自定义路由来控制当用户被定向到 ~/AccessDenied 时发生的情况:

Route route = routes.MapRoute("AccessDeniedRoute", "AccessDenied", new { controller = "MyCustomErrorController", action = "My401Action" });
RouteTable.Routes.Add(route);

关于c# - 如何在 ASP.Net MVC 3 中重定向到 ActionResult 中的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7196867/

相关文章:

java - C# 实现 - "Print all combinations of balanced parentheses"

c# - MVC onfocusout 事件未触发

C# Excel 互操作 - 从 Range 中删除第一行

c# - Identity 如何知道密码重置 token 是否已被使用?

c# - ASP.NET MVC 中的简单图形计算器,如 MS Windows 计算器

javascript - AsyncFileUpload 限制要上传的文件大小

asp.net - 如何转换类似web.config的log4net配置?

c# - 进行基础连接时,asp.net 页面加载两次

c# - 在 ASP.NET MVC 的局部 View 中确定当前 View 的名称

c# - 为什么 HttpClient 只允许异步调用? C#