我有一个带有/ api文件夹的MVC项目,其中包含我的Web API控制器.我想要以下事项:
在我的MVC站点的web.config中,我有一个httpErrors节点,并将errorMode设置为"Custom",以便在404s/500s/etc时我可以拥有漂亮的错误页面.在浏览MVC站点期间发生:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<remove statusCode="403" subStatusCode="-1" />
<error prefixLanguageFilePath="" statusCode="404" path="Content\notfound.htm" responseMode="File" />
<error statusCode="500" path="/Errors" responseMode="ExecuteURL" />
<error statusCode="403" path="/Errors/Http403" responseMode="ExecuteURL" /></httpErrors>
Run Code Online (Sandbox Code Playgroud)
但是,使用该配置,API将在发生错误时提供自定义错误页面,而不是具有异常/堆栈跟踪的json/xml(这是所需的行为).
有没有办法将自定义错误配置为仅应用于我的MVC站点而不是Web API?这篇博客说没有(http://blog.kristandyson.com/2012/11/iis-httperrors-aspnet-web-api-fully.html),但我想知道是否有其他人找到了工作自该博客发布以来.
我想如果没有,我可以为我的Web API项目创建一个单独的项目/程序集.这将允许我分别为MVC和Web API配置httpErrors,但我不想创建另一个项目,所以我还有另一个web.config来配置.
我正在编写Web API服务,如果我的ModelState无效,则尝试返回(400)错误请求.我不希望将响应主体附加到此.似乎IIS正在劫持我的响应,并且总是返回带有冗长的样式错误页面的text/html内容类型.这是个问题.
[HttpPost]
public void Link(LinkDeviceModel model)
{
if (ModelState.IsValid)
{
try
{
model.Save();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
throw new HttpResponseException(ex.Message, HttpStatusCode.InternalServerError);
}
}
else
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的小提琴请求:
POST http://localhost/myapp/service/link HTTP/1.1
Host: localhost
Content-Length: 112
Content-Type: application/json
Accept: application/json
{"DeviceUniqueId":"CC9C6FC0-7D06-11E1-8B0E-31564824019B", "UserName": "me@mycompany.com"," Pin": "111111"}
Run Code Online (Sandbox Code Playgroud)
我的回答是错误的,充满了身体,回应:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IIS 7.5 Detailed Error - 400.0 - Bad Request</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;}
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;}
.config_source code{font-size:.8em;color:#000000;}
pre{margin:0;font-size:1.4em;word-wrap:break-word;}
ul,ol{margin:10px …Run Code Online (Sandbox Code Playgroud)