asp.net-mvc-4 – 返回Web API中的自定义错误对象
发布时间:2020-05-23 10:55:36 所属栏目:asp.Net 来源:互联网
导读:我有一个Web API我正在使用MVC 4 Web API框架。如果有一个异常,我目前抛出一个新的HttpResposneException。即: if (!Int32.TryParse(id, out userId)) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest
|
我有一个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));
编辑 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()
};
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 如何修复错误名称空间’System’中不存在类
- asp.net – 哪个会员提供程序实现存储在web.config中的用户
- asp.net – 在Publish上自动压缩html和css?
- asp.net-mvc – MVC“添加控制器”是“无法检索元数据…配置
- asp.net – 引用相同主键的两个外键
- asp.net – .net 4.6框架是在位升级,那么.net framework 4.
- asp.net – 有没有办法每天在.Net Web应用程序中运行一个进
- asp.net – 多数据库同步 – 带消息背板的SignalR
- asp.net-mvc – 为MVC3 DateTime设置DataFormatString
- 如何在ASP.net中获取页面中的主页?
推荐文章
站长推荐
- asp.net – 重写规则错误:HTTP错误500.50 – UR
- 如何使用ASP.NET创建和填充ZIP文件?
- asp.net – 如何在警告框中显示验证控件的错误消
- asp.net – 当用户按下文本框中的返回时,我可以取
- asp.net – Telerik RadGrid – 如何默认编辑模式
- asp.net-mvc – 在Asp.Net MVC应用程序中使用Str
- asp.net-mvc – 强大类型的ASP.NET MVC与ADO.NET
- asp.net – 如何在捕获httpwebrequest超时后关闭
- 在ASP.NET中将HTML转换为PDF时保持CSS样式
- asp.net-mvc – 支持URL中任何位置的catch-all参
热点阅读
