我不是asp.net webapi的专家,并尝试使用自定义错误模型返回一些自定义错误响应。请在下面找到我的代码。这是正确的方法吗?基本上我有一个自定义的errormodel,我需要在webapi中出现任何异常时返回它。
public async Task<HttpResponseMessage> Get(string assetId)
{
_logProvider.Info($"AssetId - {assetId}");
try
{
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception exception)
{
return Request.CreateCustomResponse(HttpStatusCode.InternalServerError, exception.Message);
}
}
public static class ApiExtensions
{
public static HttpResponseMessage CreateCustomResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string errorMessage)
{
var errorMessageModel = new ErrorModel(statusCode, errorMessage);
return request.CreateResponse(statusCode, errorMessageModel);
}
}
public class ErrorModel
{
public ErrorModel(HttpStatusCode statusCode, string message)
{
Code = (int)statusCode;
Message = message;
Fields = new Dictionary<string, ModelErrorCollection>();
}
public ErrorModel(HttpStatusCode statusCode)
{
Code = (int)statusCode;
Fields = new Dictionary<string, ModelErrorCollection>();
}
public string Message { get; set; }
public int Code { get; set; }
public Dictionary<string, ModelErrorCollection> Fields { get; set; }
}
由于