相关疑难解决方法(0)

如何在ASP.NET MVC中正确处理404?

我正在使用RC2

使用URL路由:

routes.MapRoute(
    "Error",
     "{*url}",
     new { controller = "Errors", action = "NotFound" }  // 404s
);
Run Code Online (Sandbox Code Playgroud)

以上似乎照顾这样的请求(假设默认路由表由初始MVC项目设置):"/ blah/blah/blah/blah"

覆盖控制器本身中的HandleUnknownAction():

// 404s - handle here (bad action requested
protected override void HandleUnknownAction(string actionName) {
    ViewData["actionName"] = actionName;
    View("NotFound").ExecuteResult(this.ControllerContext);
}  
Run Code Online (Sandbox Code Playgroud)

但是,之前的策略不处理对Bad/Unknown控制器的请求.例如,我没有"/ IDoNotExist",如果我请求这个,我从Web服务器获取通用404页面而不是我的404,如果我使用路由+覆盖.

最后,我的问题是: 有没有办法在MVC框架中使用路由或其他东西来捕获这种类型的请求?

或者我应该默认使用Web.Config customErrors作为我的404处理程序并忘记所有这些?我假设如果我使用customErrors,由于Web.Config对直接访问的限制,我必须在/ Views之外存储通用404页面.

asp.net-mvc http-status-code-404

426
推荐指数
9
解决办法
13万
查看次数

配置Magical Unicorn Mvc错误工具包

我试图在我的MVC4网站上配置Magical Unicorn Mvc Error Toolkit(v 2.1.2),但我无法让它工作.这是我的代码:

Web.config文件

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error/ServerError">
    <error statusCode="404" redirect="~/Views/Error/NotFound.cshtml" />
</customErrors>

<system.webServer>
   <httpErrors errorMode="Custom" existingResponse="Replace">
     <remove statusCode="404" subStatusCode="-1" />
     <remove statusCode="500" subStatusCode="-1" />
     <error statusCode="404" path="~/Error/NotFound" responseMode="ExecuteURL" />
     <error statusCode="500" path="~/Error/ServerError" responseMode="ExecuteURL" />
   </httpErrors>
<system.webServer>
Run Code Online (Sandbox Code Playgroud)

错误控制器

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View();
    }

    public ActionResult ServerError()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

[这些是基于这个/sf/answers/524958451/帖子]

CustomerErrorHandler.cs(App_Start)

using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using WorldDomination.Web.Mvc;
using CustomErrors.App_Start;

[assembly: WebActivator.PreApplicationStartMethod(typeof(CustomErrorHander), …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc custom-errors asp.net-mvc-4

5
推荐指数
1
解决办法
1066
查看次数