[英]HTTP not found custom exception in asp.net web API
我從此處使用此代碼源在我的應用程序中顯示帶有詳細錯誤消息的自定義404。 但是ActionSelector無法正常工作,並在請求中拋出null異常
public class HttpNotFoundAwareControllerActionSelector : ApiControllerActionSelector
{
public HttpNotFoundAwareControllerActionSelector()
{
}
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
HttpActionDescriptor decriptor = null;
try
{
decriptor = base.SelectAction(controllerContext);
}
catch (HttpResponseException ex)
{
var code = ex.Response.StatusCode;
if (code != HttpStatusCode.NotFound && code != HttpStatusCode.MethodNotAllowed)
throw;
var routeData = controllerContext.RouteData;
routeData.Values["action"] = "Handle404";
IHttpController httpController = new ErrorController();
controllerContext.Controller = httpController;
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "Error", httpController.GetType());
decriptor = base.SelectAction(controllerContext);
}
return decriptor;
}
}
這是我的HttpError控制器
public class ErrorController : ApiController
{
[HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs("PATCH")]
public HttpResponseMessage Handle404()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound, Logger.ConditionWarning("Invalid API Request - 404 Not Found"));
return response;
}
}
看來SelectAction沒有將請求轉發給控制器? 請幫忙
編輯:試試這個
public class ErrorController : ApiController
{
[HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs("PATCH")]
public HttpResponseMessage Handle404()
{
HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NotFound);
message.Content = new ObjectContent(typeof(HttpResponseMessage), Logger.ConditionWarning("Invalid API Request - 404 Not Found"), GlobalConfiguration.Configuration.Formatters.JsonFormatter);
return message
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.