[英]How do I add properties to a Web API Response that I do not store in my DB?
[英]How do I add/change .NET Web API's default Json message response properties?
是的,只是使用如果您想從服務器更改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 });
如果您有控制器方法,則應返回JsonResult
如果您正在尋找通用解決方案,那么請看一下這篇文章,它可能會對您有所幫助。
可以使用自定義的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
}
}
在您的api控制器方法中,您可以使用由[Authorize]
插入的[Authorize]
[CustomAuthorizeAttribute]
[Authorize]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.