【问题标题】:Send class object to Exception Handling将类对象发送到异常处理
【发布时间】:2016-04-04 09:40:53
【问题描述】:

我想在 Web API 中实现自定义异常处理。

我能够实现一些初始实现,但是我想将类对象传递给异常以显示所有属性。喜欢

    class error
    {
      int error_code
      string error_message
      string API
    }

当出现一些错误时,它应该显示类似 json

{
"error_code": 0,
"error_message":"Either Your are not authorized or you don't have any project yet.",
"API": "save data"
}

此代码仅显示消息

throw new HttpResponseException(
                       Request.CreateErrorResponse(HttpStatusCode.NotFound, message));

任何建议,

谢谢

【问题讨论】:

    标签: c# asp.net-web-api exception-handling


    【解决方案1】:

    您只需将您的对象作为CreateResponse 方法的输入。生成错误响应如下,

    return Request.CreateResponse(HttpStatusCode.BadRequest, error, 
        new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
    

    Web API 将自动对您传递的 error 对象进行 json-fies。
    在执行此操作之前,请确保在 error 对象中设置了必要的值。
    希望这可以帮助。

    编辑
    将您的HttpStatusCode 设置为BadRequest 而不是NotFound,因为您正在生成异常。比较合适。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2012-07-05
      相关资源
      最近更新 更多