【发布时间】:2014-08-01 03:39:18
【问题描述】:
请任何人告诉我以下三个模块如何在 asp.net Web API 2.1 中协同工作
- Owin 中间件
- HttpMessageHandler(或 DelegatingHandler)
- 异常处理程序
我要做的是开发一个 web api,它将提供一个恒定格式的 json 数据,这意味着如果实际数据是
{"Id":1,"UserName":"abc","Email":"abc@xyz.com"}
那我喜欢传递json为
{__d:{"Id":1,"UserName":"abc","Email":"abc@xyz.com"}, code:200, somekey: "somevalue"}
为此,我尝试使用自定义 ActionFilterAttribute,但我觉得(仍然无法确认)如果代码遇到异常,则无法提供类似格式的数据
请建议我最好的方向。
这是我的自定义属性的简短代码sn-p。还建议我自定义属性是否适合目的
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class ResponseNormalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
var response = actionExecutedContext.Response;
object contentValue;
if (response.TryGetContentValue(out contentValue))
{
var nval = new { data=contentValue, status = 200 };
var newResponse = new HttpResponseMessage { Content = new ObjectContent(nval.GetType(), nval, new JsonMediaTypeFormatter()) };
newResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
actionContext.Response = newResponse;
}
}
}
【问题讨论】:
-
当状态码已经是响应本身的一部分时,为什么还要将其作为响应正文的一部分返回?我也觉得这是很糟糕的设计。想想一年后你什么时候回到你的代码。是否易于阅读,并且易于了解正在发生的事情?为什么不创建一个与您想要的输出相对应的模型并将其返回到您的控制器中。
-
HttpMessageHandler和ExceptionHandler是 WebAPI 的一部分。OwinMiddleware是管道的一部分,仅当您使用 OWIN 时才可用。使用ActionFilters,您离控制器很近。您甚至可以访问实际实例。 OWIN 中间件甚至早于您使用 Web API 框架。这意味着您无权访问它的服务等。
标签: asp.net json asp.net-web-api