自定义错误页面与布局 [英] Custom Error Pages with Layout

查看:127
本文介绍了自定义错误页面与布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在争取自定义错误页面的工作,并继续找回我的方式,只是使用静态页面。虽然静态页面可以正常工作,但是这样就需要重新制作我们想避免的导航栏。我正在使用以下指定自定义错误页面。



Asp.net错误处理

 < customErrors mode =OnredirectMode =ResponseRewrite> 
< error statusCode =404redirect =〜/ 404.aspx/>
< / customErrors>

IIS错误处理

 < httpErrors errorMode =自定义> 
< remove statusCode =404/>
< error statusCode =404path =/ 404.htmlresponseMode =File/>
< / httpErrors>

有没有实现动态自定义错误页面的方法,可以处理IIS错误和Asp.net错误?

解决方案

我在ASP.Net MVC项目中遇到了同样的问题,通过处理程序将所有内容通过.Net进行管理。 / p>

 < system.webServer> 
<处理程序>
< remove name =ExtensionlessUrlHandler-ISAPI-4.0_32bit/>
< remove name =ExtensionlessUrlHandler-ISAPI-4.0_64bit/>
< remove name =ExtensionlessUrlHandler-Integrated-4.0/>
< remove name =OPTIONSVerbHandler/>
< remove name =TRACEVerbHandler/>
< add name =ExtensionlessUrlHandler-ISAPI-4.0_32bitpath =*。*verb =GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSmodules =IsapiModulescriptProcessor = %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dllpreCondition =classicMode,runtimeVersionv4.0,bitness32responseBufferLimit =0/>
< add name =ExtensionlessUrlHandler-ISAPI-4.0_64bitpath =*。*verb =GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSmodules =IsapiModulescriptProcessor = %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dllpreCondition =classicMode,runtimeVersionv4.0,bitness64responseBufferLimit =0/>
< add name =ExtensionlessUrlHandler-Integrated-4.0path =*。*verb =GET,HEAD,POST,DEBUG,PUT,DELETEtype =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
< / handlers>
< /system.webServer>

首先创建了一个 ErrorController ,以处理请求错误,找不到请求,如。

  [AllowAnonymous] 
public class ErrorController:Controller {
// GET:错误
public ActionResult NotFound(){
Response.StatusCode =(int)System.Net.HttpStatusCode.NotFound;
Response.TrySkipIisCustomErrors = true;
HttpContext.Response.StatusCode =(int)System.Net.HttpStatusCode.NotFound;
HttpContext.Response.TrySkipIisCustomErrors = true;
return View();
}

public ActionResult Error(){
Response.StatusCode =(int)System.Net.HttpStatusCode.InternalServerError;
Response.TrySkipIisCustomErrors = true;
return View();
}
}

您会注意到我调用 TrySkipIisCustomErrors 尝试避免IIS错误



然后一个基本控制器来处理所有未知的操作,将映射到 ErrorController.NotFound 操作已创建。

  public abstract class FrontOfficeControllerBase:Controller {
protected override void HandleUnknownAction(string actionName){
var data = ViewData;
//自定义代码来解析视图。
// ViewResult view = this.View< ErrorController>(c => c.NotFound());

//手动创建视图数据
ViewResult view = new ViewResult();
view.ViewData = new ViewDataDictionary();
view.ViewData [controller] =Error;
view.ViewData [action] =NotFound;

if(data!= null&& data.Count> 0){
data.ToList()。ForEach(view.ViewData.Add);
}

Response.StatusCode =(int)System.Net.HttpStatusCode.NotFound;
Response.TrySkipIisCustomErrors = true;
view.ExecuteResult(this.ControllerContext);
}
}

所有控制器将从此基础控制器继承。



所有其他路由之后配置了所有路由。

  routes.MapRoute(
name:404-NotFound,
url:NotFound,
defaults:new {controller =Error ,action =NotFound}
);

routes.MapRoute(
name:500-Error,
url:Error,
defaults:new {controller =Error,action = 错误}
);

routes.MapRoute(
name:CatchAll,
url:{* any},
defaults:new {controller =Error =NotFound});

这确保如果路由与我的任何控制器不匹配,它将安全地路由到 ErrorController.NotFound action。



对于这些视图,我创建了相应的 NotFound.shtml Error.cshtml Views / Shared 文件夹中分页,他们受益于根本的布局,这是我以为你在寻找。



最后我能够删除 customErrors httpErrors web.config ,因为不再需要它们,因为每个请求都由处理程序并相应路由。



这个结构的原始想法来自于这篇文章,我混合并匹配了可用的选项,直到我找到了一个适合我的需求的解决方案。





希望这有帮助。 p>

I've been fighting to get custom error pages to work and keep finding my way back to simply using a static page. Though the static page works, it would require remaking the navigation bar which we would like to avoid at this time. I'm currently using the following to specify custom error pages.

Asp.net Error Handling

<customErrors mode="On" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="~/404.aspx"/>
</customErrors>

IIS Error Handling

<httpErrors errorMode="Custom">
  <remove statusCode="404"/>
  <error statusCode="404" path="/404.html" responseMode="File"/>
</httpErrors>

Is there a method of implementing dynamic custom error pages that can handle for both IIS errors and Asp.net errors?

解决方案

I got around the same issue in my ASP.Net MVC projects by piping everything through .Net via handlers.

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*.*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*.*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*.*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

First an ErrorController was created to handle request errors and not found requests like.

[AllowAnonymous]
public class ErrorController : Controller {
    // GET: Error
    public ActionResult NotFound() {
        Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
        Response.TrySkipIisCustomErrors = true;
        HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
        HttpContext.Response.TrySkipIisCustomErrors = true;
        return View();
    }

    public ActionResult Error() {
        Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
        Response.TrySkipIisCustomErrors = true;
        return View();
    }
}

You will notice that I call TrySkipIisCustomErrors to try to avoid IIS errors

Then a base controller to handle all unknown actions that would map to the ErrorController.NotFound action was created.

public abstract class FrontOfficeControllerBase : Controller {
    protected override void HandleUnknownAction(string actionName) {
        var data = ViewData;
        //Custom code to resolve the view.
        //ViewResult view = this.View<ErrorController>(c => c.NotFound());

        //Manually create view with view Data
        ViewResult view = new ViewResult();
        view.ViewData = new ViewDataDictionary();
        view.ViewData["controller"] = "Error";
        view.ViewData["action"] = "NotFound";

        if (data != null && data.Count > 0) {
            data.ToList().ForEach(view.ViewData.Add);
        }

        Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
        Response.TrySkipIisCustomErrors = true;
        view.ExecuteResult(this.ControllerContext);
    }
}

All Controllers would inherit from this base controller.

A catch all route was configured after all other routes.

routes.MapRoute(
    name: "404-NotFound",
    url: "NotFound",
    defaults: new { controller = "Error", action = "NotFound" }
);

routes.MapRoute(
    name: "500-Error",
    url: "Error",
    defaults: new { controller = "Error", action = "Error" }
);

routes.MapRoute(
    name: "CatchAll",
    url: "{*any}",
    defaults: new { controller = "Error", action = "NotFound" });

This made sure that if a route was not matched to any of my controllers it would safely route to the ErrorController.NotFound action.

For the views, I created the respective NotFound.shtml and Error.cshtml paged in the Views/Shared folder and they benefited from access to the root layout, which is what I think you were looking for.

In the end I was able to remove both the customErrors and httpErrors from web.config as there was no longer any need for them as every request was managed by the handlers and routed accordingly.

The original idea for this structure came from this article where I mixed and matched the available options till I found a solution that worked/suited my needs.

Exception handling in ASP.NET MVC (6 methods explained)

Hope this helps.

这篇关于自定义错误页面与布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆