asp.net-mvc-4 – 返回Web API中的自定义错误对象

我有一个Web API我正在使用MVC 4 Web API框架。如果有一个异常,我目前抛出一个新的HttpResposneException。即:
if (!Int32.TryParse(id,out userId))
    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,"Invalid id"));

这会向客户端返回一个对象,即{“message”:“无效的ID”}

我想通过返回一个更详细的对象来进一步控制对异常的响应。就像是

{
 "status":-1,"substatus":3,"message":"Could not find user"
 }

我怎么会这样做?是序列化我的错误对象和设置它在响应消息中的最佳方式吗?

我也看了ModelStateDictionary一点,并提出了这一点“黑客”,但它仍然不是一个干净的输出

var msd = new ModelStateDictionary();
msd.AddModelError("status","-1");
msd.AddModelError("substatus","3");
msd.AddModelError("message","invalid stuff");
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,msd));

编辑
看起来像一个自定义的HttpError是我需要的。这似乎做的伎俩,现在使它可以从我的业务层扩展…

var error = new HttpError("invalid stuff") {{"status",-1},{"substatus",3}};
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,error));

解决方法

这些答案比他们需要的更复杂。
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new HandleApiExceptionAttribute());
        // ...
    }
}

public class HandleApiExceptionAttribute : ExceptionFilterattribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        var request = context.ActionContext.Request;

        var response = new
        {
             //Properties go here...
        };

        context.Response = request.CreateResponse(HttpStatusCode.BadRequest,response);
    }
}

这就是你需要的。它也很好,容易的单元测试:

[Test]
public async void OnException_ShouldBuildProperErrorResponse()
{
    var expected = new 
    {
         //Properties go here...
    };

    //Setup
    var target = new HandleApiExceptionAttribute()

    var contextMock = BuildContextMock();

    //Act
    target.OnException(contextMock);

    dynamic actual = await contextMock.Response.Content.ReadAsAsync<ExpandoObject>();

    Assert.AreEqual(expected.Aproperty,actual.Aproperty);
}

private HttpActionExecutedContext BuildContextMock()
{
    var requestMock = new HttpRequestMessage();
    requestMock.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration());

    return new HttpActionExecutedContext()
    {
        ActionContext = new HttpActionContext
        {
            ControllerContext = new HttpControllerContext
            {
                Request = requestMock
            }

        },Exception = new Exception()
    };
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....