2017-02-27 32 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