ASP.NET MVC 5错误处理中如何获取请求的原始方法与URI
解决ASP.NET MVC自定义404页面丢失原始请求信息的问题
当使用responseMode="ExecuteURL"时,IIS会发起内部重定向至错误处理页面,此时Request对象指向的是错误页面的URL,而非触发404的原始请求信息。可通过以下两种方案获取原始请求的方法与URI:
方法一:读取IIS传递的服务器变量
修改ErrorController的NotFound方法,从服务器变量或错误上下文提取原始请求数据:
public class ErrorController : Controller { public ActionResult NotFound() { Response.StatusCode = 404; // 获取原始请求URL string originalUrl = Server.GetLastError()?.HttpRequest?.RawUrl ?? Request.ServerVariables["HTTP_X_ORIGINAL_URL"] ?? $"{Request.ServerVariables["SCRIPT_NAME"]}{Request.ServerVariables["QUERY_STRING"]}"; // 获取原始请求方法 string originalMethod = Request.ServerVariables["HTTP_X_HTTP_METHOD_OVERRIDE"] ?? Request.ServerVariables["REQUEST_METHOD"]; ViewBag.Message = $"{originalMethod} {originalUrl} not supported"; return View(); } }
方法二:修改Web.Config的responseMode(URL会跳转)
若允许URL跳转到错误页面,可将responseMode设为Redirect,通过查询参数传递原始请求信息:
- 修改Web.Config配置:
<system.webServer> <httpErrors errorMode="Custom" existingResponse="Replace" > <remove statusCode="404"/> <error statusCode="404" path="/Error/NotFound?originalUrl={REQUEST_URI}&originalMethod={REQUEST_METHOD}" responseMode="Redirect"/> </httpErrors> </system.webServer>
- 修改Controller方法接收参数:
public ActionResult NotFound(string originalUrl, string originalMethod) { Response.StatusCode = 404; ViewBag.Message = $"{originalMethod} {originalUrl} not supported"; return View(); }
额外配置提示
如果是早期MVC版本,需确保system.web节点下的customErrors配置同步生效:
<system.web> <customErrors mode="On" redirectMode="ResponseRewrite"> <error statusCode="404" redirect="~/Error/NotFound"/> </customErrors> </system.web>
内容的提问来源于stack exchange,提问作者Hovanella
相关产品推荐
相关产品推荐

