添加其他JSON结构到所有的WebAPI的回应? [英] Add additional json structure to all WebApi's responses?
问题描述
的我们正在与移动软件公司整合做我们在移动设备应用程序。的
我们的控制器(简化)方法一样:
Our controller has ( simplification) methods like :
api/users/1
–GetUserById(...)
api/users/changePassword
–ChangePassword(Person p)
确定。
的的ChangePassword
可以返回一些应用性的错误codeS(密码已经使用,密码太短,密码喇嘛喇嘛...)
The ChangePassword
can return several applicative error codes ( password has already used , password too short , password bla bla...)
所以,如果,例如,密码已经被使用,那么的Http code
应 200
额外的信息返回
So if ,for example, password has already been used , then the HttpCode
should be 200
returned with additional info
我们同意此约定每个响应:( 其他,以响应数据)
We agreed on this convention for every response :( additional to the response data)
{
"Success":0,
"ErrorCode": 6,
"ErrorMessage":"already used"
}
但这种结构,正如我所说的 - 应该是在每一个响应
But this structure , as I said - should be in every response.
所以,到现在为止 - 例如: API /用户/ 1
返回:
So till now - for example : api/users/1
returned :
{
"userId":1,
"name":"John"
}
但现在 - 的反应应该是:
But now - the response should be :
{
"data":
{
"userId":1,
"name":"John"
}
,
"result": //no errors
{
"Success":0,
"ErrorCode": 0,
"ErrorMessage":""
}
}
他们一直在寻找的结果对象,以应用型反应。
They always looking for the "result" object to see the applicative response.
问
我认为这是我应该做的地方正是在消息处理程序后, base.SendAsync
(响应部分)
I assume that the place which I should do it is in message handler after base.SendAsync
( response part)
不过,我应该怎么换,我通过 Request.CreateResponseMessage
发送带有格式+值常规响应:
But how should I wrap the regular response which I send via Request.CreateResponseMessage
with the format + values of :
NB,当然在 Request.CreateResponseMessage
阶段我已经有相应的结果$ C $结果对象CS。
NB , of course at the Request.CreateResponseMessage
phase I already have result object with the appropriate result codes.
推荐答案
通过在网页API管线运行时消息处理程序,您的操作方法已经产生将被序列化的结果。一个动作过滤器将是一个更好的选择,因为你可以对付的对象,你可以做这样的事情。
By the time message handlers run in Web API pipeline, the result your action method has produced would have been serialized. An action filter would be a better option, since you can deal with objects, and you can do something like this.
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext context)
{
var content = context.Response.Content as ObjectContent;
if (content != null)
{
content.Value =
new MyResponse()
{
Result = new Result() { Success = 0, ErrorCode = 6 },
Data = content.Value
};
}
}
}
public class Result
{
public int Success { get; set; }
public int ErrorCode { get; set; }
}
public class MyResponse
{
public Result Result { get; set; }
public object Data { get; set; }
}
注:以上code将只对JSON和XML不是
Note: The above code will work only for JSON and not XML.
这篇关于添加其他JSON结构到所有的WebAPI的回应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!