簡體   English   中英

如何添加/更改.NET Web API的默認Json消息響應屬性?

[英]How do I add/change .NET Web API's default Json message response properties?

以Web API中未經授權的調用為例,它將提供相應的響應。

圖片

  1. 有沒有一種方法可以將默認屬性名稱“消息”更改為另一個名稱,例如“原因” /“描述”,以獲取不成功的API響應?

  2. 是否可以添加“狀態”之類的新屬性?

是的,只是使用如果您想從服務器更改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

如果您正在尋找通用解決方案,那么請看一下這篇文章,它可能會對您有所幫助。

http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information

可以使用自定義的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM