本文介绍了处理ASP.NET MVC时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行错误处理(403、404、500)。我做了 ErrorController Views

I'm making error handling (403, 404, 500). I made ErrorController and Views:

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

}

然后我在 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));
}

在具有控制器名称的url时有效(例如: http:// localhost:62693 / News / 123 ),然后出现错误的404视图。

It works when url with controller name (example: http://localhost:62693/News/123), then I got error's 404 view.

但是当我发送不带控制器名称的url时或无效的控制器名称(例如: http:// localhost:62693/123 http:// localhost:62693 / new / k )我只有 HTML 错误代码的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.

如何获取错误404视图中是否包含任何网址?

How can I get error's 404 view with any urls?

推荐答案

解决我的问题只需添加

Response.ContentType = text / html;

其他方法:

我找到了其他自定义错误的方法。

I find some other way to make custom errors.

web.config

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

控制器

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

这对我有用。

这篇关于处理ASP.NET MVC时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:04