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();
public class NotImplExceptionFilter : ExceptionFilterAttribute {
public override void OnException(HttpActionExecutedContext context) {
if (context.Exception is NotImplementedException) {
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
}
}
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 }
);
}
}
10 回答
我有同样的问题,但它的来源略有不同:我错误地设置
CORS
政策,这给了我500 Internal server error
,但由于CORS
无法正常工作,Access-Control-Allow-Origin
Headers 未在响应中显示,浏览器无法读取实际响应我用ChromeDevTools选项
Copy as cURL
解决了这个问题,它允许我查看响应并了解错误来源发布RC后,此问题已得到修复,除了500内部服务器错误之外,您还将收到错误详细信息 . (仅针对Web主机方案修复此问题) .
您可以执行以下操作以获取格式化程序的WriteToStream方法期间可能发生的实际异常的详细信息 .
您可以尝试添加:
到Global.asax中的
Application_Start()
. 此解决方案适用于许多常见错误 .但是,如果您没有获得满意的信息,则应考虑编写l Exception Filter 并在全球注册 .
This article应该让你入门 . 您需要的核心是编写和注册以下内容:
我遇到了同样的问题 . 我发现Kiran Challa's response有助于在我的操作之外抛出实际的异常 .
为了解决我的问题,setting the ProxyCreationEnabled property of my context to false让我更进了一步 .
在我的场景中,我的下一个例外是由于模型中的循环引用 . 清理完之后,幻影500的响应消失了 . 祝你好运,如果你还没有解决这个问题!
这可能与循环引用有关 .
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#handling_circular_object_references
尝试将以下代码添加到Global.asax文件中的Application_Start方法:
在我的案例中,一个欺骗性的简单路由弱点导致了这个问题:在我的Api控制器中有另一个具有相同签名(不是名称)的HttpPost . 默认路由不解析名称差异,ServiceError 500是在达到任一Api函数之前给出的响应 . 解决方案:更改默认路由或签名,然后重试 .
这是我的RouteConfig.cs,它适用于标准的WebApi2用法:
当我没有按正确的顺序指定查询参数时,我在RC中遇到了问题 . 例如,如果指定
$skip=0
,它将获得500,但如果指定$orderby=xxx&skip=0
则无错误 .我通常使用Global.asax来捕获所有错误 . 这是您可以使用的代码片段
此场景的原因如下
由于Web.config格式错误而导致出现问题 . (多个configSections)
我没有在 bin 文件夹中创建 roslyn 文件夹,而是在根目录创建了它 . (部署位置 . )
诊断这个问题的最佳方法是,在应用程序位置放置一个简单的HTML页面并尝试浏览它 . 500错误描述将显示在此html页面上 .
而且别忘了添加
到Web.config
FredrikNormén撰写了一篇名为ASP.NET Web API Exception Handling的博文,内容涉及该主题 . 他的解决方案使用自定义异常类和可应用于所有
ApiController
操作方法的异常过滤器属性 .