包含WebApi2控制器的.NET MVC应用程序。经过一些谷歌搜索,我了解到这是一种在api控制器中处理错误的正确方法,通过抛出带有适当状态代码的HttpResponseException:
控制器动作方法:
[System.Web.Http.Authorize]
public IHttpActionResult GetEntities() {
var entsDb = db.MyEntities;
/*
//uncomment this block to test exception throw
var response = new HttpResponseMessage(HttpStatusCode.NotFound) {
Content = new StringContent("some error message", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
};
throw new HttpResponseException(response);
*/
Dictionary<int, string> ents = entsDb.ToDictionary(k => k.id, v => v.name);
return Ok(ents);
}然后在消费者中,我可以捕获异常并访问消息等。消费者请求:
using (var client = new HttpClient()) {
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token.Access_Token);
HttpResponseMessage response = await client.GetAsync("Api/GetEntities/");
if (response.IsSuccessStatusCode) {
Dictionary<int, string> listEnts = await response.Content.ReadAsAsync<Dictionary<int, string>>();
return listEnts;
}
else {
var s = response.Content.ReadAsStringAsync();
s.Wait();
throw new Exception("An error ocurred. Server response: "+s.Result);
}
}在上面的代码中,如果我取消注释异常块(在控制器操作方法中),它会按预期工作,消费者会得到异常,并可以访问其消息等。
这在开发中工作正常,但是当我将mvc/webapi项目部署到生产服务器时,每当出现错误时,我没有收到异常,而只是收到一条消息“页面无法显示,因为发生了内部服务器错误”。
我猜这是因为web.Release.config配置更改了生产服务器上的"debug“开关,在Web.Release.config中有下面这一行:
<compilation xdt:Transform="RemoveAttributes(debug)"/>因此,对于这种配置,在dev中它将显示详细的错误,但在生产中它将显示一般错误。
但是我不知道如何解决这个问题。有没有办法让它在产品服务器中为mvc请求返回一般错误,而不是为WebApi请求返回?顺便问一下,这真的是处理WebApi中错误的正确方法吗?
**更新:**好吧,显然我的猜测是错误的。我重新部署了它,删除了web.release.config中的那行代码,它也是这样做的。此外,如果我在本地主机上运行webapi,但在发布模式下运行,它可以工作。所以它不能在服务器上工作。也许是一些IIS参数或者别的什么?
发布于 2019-09-23 00:48:19
好了,我终于找到了错误,它在web.config中。我把它放在这里以防它能帮上什么人。
在这篇文章之后,Is it possible to use custom error pages with MVC site but not Web API?
在我的web.config中,我添加了如下自定义错误页面:
<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" defaultPath="/Error/Index" errorMode="Custom">
<remove statusCode="404"/>
<remove statusCode="400"/>
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="400" responseMode="ExecuteURL" path="/Error/Forbidden" />
</httpErrors>然后我有了这个代码块,以便api调用忽略自定义错误页面,并返回原始错误,如下所示
<location path="Api">
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
<clear/>
</httpErrors>
</system.webServer>
</location>我只需要删除行<clear/>,现在一切都正常了。
https://stackoverflow.com/questions/58049623
复制相似问题