[英]How do I add/change .NET Web API's default Json message response properties?
Using the example of an unauthorized call in web API, it will provide a response as per this. 以Web API中未经授权的调用为例,它将提供相应的响应。
Is there a way to change the default property name "Message" to another name like "Reason"/"Description" for non-success API responses? 有没有一种方法可以将默认属性名称“消息”更改为另一个名称,例如“原因” /“描述”,以获取不成功的API响应?
Is it possible to add a new property like "Status"? 是否可以添加“状态”之类的新属性?
Yes just use If you want to change the structure of the Josn response return from the server you can create new response by using follwing code in asp.net mvc app . 是的,只是使用如果您想从服务器更改Josn响应返回的结构,则可以使用asp.net mvc应用程序中的以下代码来创建新响应。
// here you can use your own properties which then can be send to client .
return Json(new { Status= false ,Description = response.Message });
if you have the controller method then you should return JsonResult 如果您有控制器方法,则应返回JsonResult
If you are looking for a generic solution then please have a look at this article it might help you . 如果您正在寻找通用解决方案,那么请看一下这篇文章,它可能会对您有所帮助。
http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information
It can be done with a custom AuthorizeAttribute. 可以使用自定义的AuthorizeAttribute来完成。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute ()
{
}
public override void OnAuthorization(HttpActionContext actionContext)
{
try
{
if (Authorize(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
catch (Exception)
{
//create custom response
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.OK,
customresponse
);
return;
}
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
//create custom unauthorized response
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.OK,
customunauthorizedresponse
);
return;
}
private bool Authorize(HttpActionContext actionContext)
{
//authorization logics
}
}
in your api controller method you can use [CustomAuthorizeAttribute]
insted of [Authorize]
在您的api控制器方法中,您可以使用由
[Authorize]
插入的[Authorize]
[CustomAuthorizeAttribute]
[Authorize]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.