C# 如何在自定义HandleErrorAttribute中获取http状态代码
我正在使用一个自定义HandleErrorAttribute,它通过在过滤器中注册而全局应用。问题是,我无法捕获正确的http错误代码。每次该属性中有200个代码C# 如何在自定义HandleErrorAttribute中获取http状态代码,c#,asp.net-mvc,C#,Asp.net Mvc,我正在使用一个自定义HandleErrorAttribute,它通过在过滤器中注册而全局应用。问题是,我无法捕获正确的http错误代码。每次该属性中有200个代码 public class HandleAndLogErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (filterContext.Ex
public class HandleAndLogErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
return;
var statusCode = filterContext.HttpContext.Response.StatusCode; //always 200
LogManager.Error(filterContext.Exception);
filterContext.Result = CreateActionResult(filterContext, statusCode);
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = statusCode;
//filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
protected virtual ActionResult CreateActionResult(ExceptionContext filterContext, int statusCode)
{
var ctx = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
var statusCodeName = ((HttpStatusCode)statusCode).ToString();
var viewName = "~/Views/Shared/Error.cshtml";
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
var result = new ViewResult
{
ViewName = viewName,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
};
result.ViewBag.StatusCode = statusCode;
return result;
}
}
通过查看的源代码,您似乎可以使用以下代码获得状态代码
var statusCode = new HttpException(null, filterContext.Exception).GetHttpCode();
是否可以尝试通过新的HttpExceptionnull、filterContext.Exception.GetHttpCode获取状态代码