我正在使用here中的此代码源在我的应用程序中显示带有详细错误消息的自定义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没有将请求转发给控制器?请帮忙
答案 0 :(得分:0)
编辑:试试这个
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
}
}