【问题标题】:.NET web API exception error details.NET Web API 异常错误详细信息
【发布时间】:2013-03-18 10:34:44
【问题描述】:

我对 Web API 非常陌生,并且正在尝试一些 API 控制器异常。我的问题是当抛出异常时,应用程序将返回太多信息,其中包括堆栈跟踪和正在返回的模型的一些属性。我想知道返回的异常是否可以仅限于一条消息?

这是一个例子:

public IEnumerable<Appointments> GetAll(int id)
{
    IEnumerable<Appointments> appointments = icdb.Appointments.Where(m => m.Id== id).AsEnumerable();
    return appointments;
}

如果这会返回异常(差异问题),它将返回如下内容:

{"Message":"发生错误。","ExceptionMessage":"The “ObjectContent`1”类型无法序列化响应正文 内容类型'应用程序/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An 发生错误。","ExceptionMessage":"自引用循环 检测到具有类型的属性“UpdateBy” 'System.Data.Entity.DynamicProxies.User_B23589FF57A33929EC37BAD9B6F0A5845239E9CDCEEEA24AECD060E17FB7F44C'。 小路 '[0].UpdateBy.UserProfile.UpdateBy.UserProfile'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":....... ...... : : : }

正如您所注意到的,它会返回一个堆栈跟踪,其中包含我模型的大部分属性。有没有办法在抛出异常时只返回一条消息?

【问题讨论】:

    标签: c# entity-framework serialization asp.net-web-api json.net


    【解决方案1】:

    您提到您有一个 API 控制器。如果遇到错误,您应该这样做:

    // A handled exception has occurred so return an HTTP status code
    return Request.CreateResponse<string>(HttpStatusCode.BadRequest, your_message);
    

    所以对于你给定的示例代码,你可以有这样的东西:

    public IEnumerable<Appointments> GetAll(int id)
    {
        IEnumerable<Appointments> appointments= null;
        try {
            icdb.Appointments.Where(m => m.Id== id).AsEnumerable();
        }
        catch {
            var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
            message.Content = new StringContent("some custom message you want to return");
            throw new HttpResponseException(message);
        }
        return appointments;
    }
    

    如果您的控制器遇到未处理的异常,调用代码将收到 500 状态。

    【讨论】:

    • 哦,太好了,我不知道我可以退货!
    猜你喜欢
    • 2011-03-20
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多