.NET Web API异常错误详细信息

时间:2013-03-28 04:18:22

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

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

以下是一个例子:

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

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

  

{“消息”:“发生错误。”,“ExceptionMessage”:“   'ObjectContent`1'类型无法序列化响应主体   内容类型'application / json;   字符集= UTF-8' “” ExceptionType。 “:” System.InvalidOperationException “ ”堆栈跟踪“:空 ”的InnerException“:{ ”消息“:” 一个   错误已经发生。“,”ExceptionMessage“:”自引用循环   使用类型检测属性“UpdateBy”   'System.Data.Entity.DynamicProxies.User_B23589FF57A33929EC37BAD9B6F0A5845239E9CDCEEEA24AECD060E17FB7F44C'。   路径   '[0] .UpdateBy.UserProfile.UpdateBy.UserProfile' “” ExceptionType。 “:” Newtonsoft.Json.JsonSerializationException”, “堆栈跟踪”:.................. ................             :             :             :}

正如您所注意到的,它会返回包含模型大部分属性的堆栈跟踪。是否有一种方法可以在抛出异常时返回消息?

1 个答案:

答案 0 :(得分:2)

您提到您有一个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状态。

相关问题