【发布时间】:2017-08-28 16:49:46
【问题描述】:
我正在开发 Web 应用程序,这是我处理异常的方式:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
LogManager.GetCurrentClassLogger().Error(ex);
Response.Clear();
Server.ClearError();
HttpException httpEx = ex as HttpException;
if (httpEx == null)
httpEx = new HttpException(400, ex.Message, ex);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Handler");
routeData.Values.Add("exception", httpEx);
Response.TrySkipIisCustomErrors = true;
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Error");
c.Execute(rc);
}
当发生异常时(例如:throw new ArgumentException("Generator with given Id does not exist.");),用户会收到错误视图,其中包含有关发生情况的详细信息。
问题是,错误消息没有在 HttpResponseMessage 中发送给用户(作为 ReasonPhrase 或其他任何东西)。
private async void DeleteGenerator(Guid id)
{
var response = await dataService.RemoveGenerator(id);
if ((int)response.StatusCode >= 300)
MessageBox.Show( /* Error message from response */ );
}
在这里我应该收到带有"Generator with given [...]" 的盒子,但我不知道如何实现。我试过this,但“HttpError”不见了,this 但我真的不知道如何在我的代码中实现它(如何通过 Application_Error 发送实际的 HttpResponseMessage)和this 但我又没有提示应该如何改变它。
编辑
这是我的常规错误处理程序控制器:
public ActionResult Handler(HttpException exception)
{
Response.ContentType = "text/html";
if (exception != null)
{
Response.StatusCode = exception.GetHttpCode();
ViewBag.StatusString = (HttpStatusCode)exception.GetHttpCode();
return View("Handler", exception);
}
return View("Internal");
}
我已经出于测试目的尝试过此操作,但它也无法正常工作(客户端收到带有“错误请求”的 HttpResponseMessageReasonPhrase。
public HttpResponseMessage Handler(HttpException exception)
{
Response.ContentType = "text/html";
if (exception != null)
{
return new HttpResponseMessage
{
Content = new StringContent("[]", new UTF8Encoding(), "application/json"),
StatusCode = HttpStatusCode.NotFound,
ReasonPhrase = "TEST"
};
}
return null;
}
【问题讨论】:
-
您是否设置了断点并检查了消息被丢弃的位置或是否曾经生成过?
-
问题是,消息可能根本没有发送。我查看了所有 HttpStatusResponse 并没有找到该消息。我想这是因为 HttpException 根本没有以我处理它的方式发送它
-
您不能在 Web 应用程序中使用
MessageBox.Show。该消息框将显示在服务器上,没有人可以看到或关闭它。 (在开发过程中似乎可以工作,因为你的机器既是服务器又是客户端) -
我没有在网络上使用 MessageBox,那是我的桌面 WPF 应用程序,它向实际的 ASP.NET 应用程序发送请求。该框仅用于调试目的,这里的主要主题是如何使用 HttpClient 从 ASP.NET 应用程序中检索异常消息
标签: c# asp.net asp.net-mvc httpclient httpresponsemessage