简体   繁体   English

处理ASP.NET MVC时出错

[英]Error handling ASP.NET MVC

I'm making error handling (403, 404, 500). 我正在进行错误处理(403,404,500)。 I made ErrorController and Views : 我制作了ErrorControllerViews

public class ErrorController : Controller
{
    // GET: Error
    public ActionResult General(Exception exception)
    {
        return View("Exception", exception);
    }

    public ActionResult Http404()
    {
        return View();
    }

    public ActionResult Http403()
    {
        return View();
    }

} 

Then I wrote the following code in Global.asax.cs : 然后我在Global.asax.cs编写了以下代码:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    log.Error(exception);
    Response.Clear();
    var httpException = exception as HttpException;
    var routeData = new RouteData();
    routeData.Values.Add("controller", "Error");

    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();

        switch (Response.StatusCode)
        {
            case 403:
                routeData.Values.Add("action", "Http403");
                break;
            case 404:
                routeData.Values.Add("action", "Http404");
                break;
            default:
                routeData.Values.Add("action", "Error");
                break;
        }
    }
    else
    {
        routeData.Values.Add("action", "General");
        routeData.Values.Add("exception", exception);
    }

    Server.ClearError();
    Response.TrySkipIisCustomErrors = true;
    IController errorsController = new ErrorController();
    errorsController.Execute(new RequestContext(
        new HttpContextWrapper(Context), routeData));
}

It works when url with controller name (example: http://localhost:62693/News/123 ), then I got error's 404 view. 它在带有控制器名称的url(例如: http://localhost:62693/News/123 )时有效,然后我得到了错误的404视图。

But when I send url without controller name in it or with invalid controller name (example: http://localhost:62693/123 or http://localhost:62693/new/k ) I got only HTML code of error's 404 view. 但是当我发送没有控制器名称或无效控制器名称的url(例如: http://localhost:62693/123http://localhost:62693/new/k )时,我只获得了错误404视图的HTML代码。

How can I get error's 404 view with any urls? 如何使用任何网址获取错误的404视图?

Add this on webConfig file webConfig文件中添加此项

<system.web>  
    <customErrors mode="On" defaultRedirect="~/Error/DefaultError">
</system.web>

// ErrorController ActionResult method...
public ActionResult DefaultError()
{
 return view();
}

handle error using RouteConfig 使用RouteConfig处理错误

You use route constraints to restrict the browser requests that match a particular route. 您使用路由约束来限制与特定路由匹配的浏览器请求。 You can use a regular expression to specify a route constraint. 您可以使用正则表达式指定路径约束。

Note : The custom router must be added to the RouterConfig file. 注意: 必须将自定义路由器添加到RouterConfig文件中。

This new {productId = @"\\d+" } is a RouteConstraints 这个new {productId = @"\\d+" }是一个RouteConstraints

  routes.MapRoute(
             "Product",
             "{controller}/{action}/{productId}",
             new {controller="Home", action="Product"},
             new {productId = @"\d+" }
            );

If the controlloller itself does not exist, IIS uses the preset 404 error page. 如果controlloller本身不存在,IIS将使用预设的404错误页面。 Look at .net error pages in IIS features view. 查看IIS功能视图中的.net错误页面。

TO SOLVE MY PROBLEM just add 解决我的问题只需添加

Response.ContentType = "text/html";

Other method: 其他方法:

I find some other way to make custom errors. 我找到了一些其他方法来制作自定义错误。

web.config web.config中

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" />
    <error statusCode="404" responseMode="ExecuteURL" path="/Error/Http404" />
  </httpErrors>
</system.webServer>

Controller 调节器

public class ErrorController : Controller
{
    public ActionResult PageNotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

This works for me. 这适合我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM