public class NotImplExceptionFilter : ExceptionFilterAttribute {
public override void OnException(HttpActionExecutedContext context) {
if (context.Exception is NotImplementedException) {
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
}
}
ObjectContent<IEnumerable<Product>> responseContent = new ObjectContent<IEnumerable<Product>>(db.Products.Include(p => p.ProductSubcategory).AsEnumerable(), new XmlMediaTypeFormatter()); // change the formatters accordingly
MemoryStream ms = new MemoryStream();
// This line would cause the formatter's WriteToStream method to be invoked.
// Any exceptions during WriteToStream would be thrown as part of this call
responseContent.CopyToAsync(ms).Wait();
在我的例子中,一个极其简单的路由缺陷导致了这个问题: 在我的 Api 控制器中有另一个具有相同签名(不是名称)的 HttpPost。默认的路由没有解决名称差异,ServiceError 500是它在到达任何一个 Api 函数之前给出的响应。解决方案: 更改默认路由或签名,然后重试。
下面是我的 RouteConfig.cs,它非常适合于标准的 WebApi2使用:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Default is required in any case.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}