请有人告诉我一下如何在asp.net Web API 2.1中一起使用三个模块
我要做的是开发一个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 ,但我觉得(仍未确认)在代码遇到异常时无法提供类似格式的数据
请建议我最好的方向。
以下是我的自定义属性的简短代码段。另外建议我自定义属性是有用的
[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;
}
}
}
答案 0 :(得分:0)
如果您不使用Owin中间件,可以全局包装所有响应,这样它将使用委托处理程序返回您的常量格式json数据。
编写一个继承自DelegatingHandler的自定义处理程序:
public class ApiResponseHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
return BuildResponse(request, response);
}
private static HttpResponseMessage BuildResponse(HttpRequestMessage request, HttpResponseMessage response)
{
object content;
string errorMessage = null;
if (response.TryGetContentValue(out content) && !response.IsSuccessStatusCode)
{
HttpError error = content as HttpError;
if (error != null)
{
content = null;
errorMessage = error.Message;
}
}
var newResponse = request.CreateResponse(response.StatusCode, new ApiResponse((int)response.StatusCode, content, errorMessage));
foreach (var header in response.Headers)
{
newResponse.Headers.Add(header.Key, header.Value);
}
return newResponse;
}
}
//ApiResponse is your constant json response
public class ApiResponse
{
public ApiResponse(int statusCode, object content, string errorMsg)
{
Code = statusCode;
Content = content;
Error = errorMsg;
Id = Guid.NewGuid().ToString();
}
public string Error { get; set; }
//your actual data is mapped to the Content property
public object Content { get; set; }
public int Code { get; private set; }
public string Id { get; set; }
}
在WebApiConfig.cs
注册处理程序:
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
...
config.MessageHandlers.Add(new ApiResponseHandler());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
...
}
我在SO中发布了类似的答案,但这是在.NET Core中并作为OWIN中间件实现(因为DelegatingHandler已经在.NET Core中消失了)。 How can I wrap Web API responses(in .net core) for consistency?