C#asp.net webapi返回带有自定义错误模型的默认自定义错误响应

时间:2016-06-23 11:29:04

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

我不是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; }
}

由于

0 个答案:

没有答案