2017-02-27 31 views

回答

0

是隻使用如果你想改變的來自服務器的響應Josn回報結構,你可以創建由asp.net的MVC應用程序中使用follwing代碼新的響應。

// 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

+0

嗨@Yashveer的,實際上,我在尋找深入更多的東西在那裏甚至還沒有達到控制器動作。無論是401未授權,還是其他一些非200響應。 – Kes

+0

@Kes能否請您提供更多信息,例如您希望在何處實施該項目。一個可能的答案是另一個答案是使用AuthorizeAttribute。創建一個自定義類,當控制器上存在Authorize屬性時將會調用該類。 –

+0

@Kes指定你的項目類型也到目前爲止你嘗試過什麼 –

0

它可以用自定義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控制方法

可以使用[CustomAuthorizeAttribute] insted的[Authorize]

+0

非常感謝自定義授權指針。但是,有沒有辦法在全球範圍內應用這種方法而不是僅僅授權?因爲可能有其他回覆,比如{「Message」:「請求無效。」 }。 – Kes