[英]How to get the http status code in custom HandleErrorAttribute
我正在使用自定義的HandleErrorAttribute,該屬性通過在過濾器中注冊來全局應用。 問題是,我找不到正確的http錯誤代碼。 每次在該屬性中包含200個代碼。
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;
}
}
瀏覽HandleErrorAttribute.cs的源代碼,看起來您可以使用以下代碼來獲取狀態代碼。
var statusCode = new HttpException(null, filterContext.Exception).GetHttpCode();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.