0

我正在开发 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 [...]",但我不知道如何实现。我已经尝试过,但是缺少“HttpError”,但是我真的不知道如何将它实现到我的代码中(如何通过 Application_Error 发送实际的 HttpResponseMessage),但是我再次不知道应该如何更改它.


编辑

这是我的常规错误处理程序控制器:

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");
}

而且我已经出于测试目的尝试过此操作,但它也无法正常工作(客户端收到HttpResponseMessage“错误请求”为ReasonPhrase.

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;
}
4

1 回答 1

0

因此,在我Controller负责显示错误视图(在方法中创建和触发)中,Application_Error我已将. 这并不理想,它会覆盖实际的 StatusCode 字符串,但它可以工作。StatusDescriptionResponse

public class ErrorController : Controller
{
    public ActionResult Handler(HttpException exception)
    {
        Response.ContentType = "text/html";
        if (exception != null)
        {
            Response.StatusCode = exception.GetHttpCode();
            Response.StatusDescription = exception.Message;
            ViewBag.StatusString = (HttpStatusCode)exception.GetHttpCode();

            return View("Handler", exception);
        }

        return View("Internal");
    }
}
于 2017-09-01T14:05:09.253 回答