2015-10-15 62 views
0

我想编写Web API进行应用程序开发人员,我要像下面如何处理,我在asp.net网页API想要的结果

当异常样本的API结果:

{ 
    "StatusCode": "0", 
    "Message": "There's exception when calling web api" 
} 

正常:json字符串中的结果是web api操作中的返回类型。

{ 
    "StatusCode": "1", 
    "Message": "Action completed successful", 
    "Result": {} 
} 

如果操作为:

public DemoController : ApiController 
{ 
    public class DemoModel 
    { 
     public string X {get;set;} 
     public int Y {get;set;} 
    } 

    [HttpGet] 
    public DemoModel GetModel(int id) 
    { 
     return new DemoModel() { X = "Demo return string" , Y = 1234}; 
    } 
} 

JSON字符串应该是成功地调用动作时,下面的示例。

{ 
    "StatusCode": "1", 
    "Message": "Action completed successful", 
    "Result": { 
     "X": "Demo return string", 
     "Y": 1234 
    } 
} 

,当异常,应该是:

{ 
    "StatusCode": "0", 
    "Message": "There's exception when calling web api" 
} 

因此,应用程序开发人员可以在web API帮助页面的返回类型的详细信息。

那是容易实现的?以及如何做(没有细节,只是逻辑,还详细越好。)

感谢大家!

+0

返回该对象作为结果'return this.Ok(yourObject);' – Fabio

+0

@Fabio然后返回类型不匹配方法声明,对吧?那么什么是合适的返回类型? – mason

+0

返回类型将IHttpActionResult和客户端'Result'值可以基于'StatusCode'使用 – Fabio

回答

0

应该创建DelegatingHandler为包装你从服务器的所有响应:

public class WrappingResponseHandler : DelegatingHandler 
{ 
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
                   CancellationToken cancellationToken) 
    { 
     HttpResponseMessage response = await base.SendAsync(request, cancellationToken); 

     return BuildApiResponse(request, response); 
    } 

    private static HttpResponseMessage BuildApiResponse(HttpRequestMessage request, HttpResponseMessage response) 
    { 
     object result; 
     string message = null; 
     int status; 
     if (response.TryGetContentValue(out result) == false || response.IsSuccessStatusCode == false) 
     { 

      var error = result as HttpError; 
      if (error != null) 
      { 
       result = null; 
      } 

      message = "There's exception when calling web api"; 
      status = 0; 
     } 
     else 
     { 
      message = "Action completed successful"; 
      status = 1; 
     } 

     HttpResponseMessage newResponse = request.CreateResponse(response.StatusCode, 
      new ApiResponse() { Message = message, Result = result, StatusCode = status }); 

     foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers) 
     { 
      newResponse.Headers.Add(header.Key, header.Value); 
     } 

     return newResponse; 
    } 

    public class ApiResponse 
    { 
     public int StatusCode { get; set; } 
     public string Message { get; set; } 
     public object Result { get; set; } 
    } 
} 

而且在WebApiConfig添加此处理程序:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     config.MessageHandlers.Add(new WrappingResponseHandler()); //here 

     // Web API configuration and services 
     // Configure Web API to use only bearer token authentication. 
     config.SuppressDefaultHostAuthentication(); 
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 

而且什么事都不会改变,并添加了控制器。

+0

它适合我,非常感谢你。 –

+0

如果我的回答很有帮助,请将其标为正确 –

0

使用IHttpActionResult将真正有帮助,尤其是如果你对应用程序开发人员的想法。它的工作原理非常具有像200(OK)等

下面是简单的代码示例,其中基于回报你获得的产品,并返回相应的响应HTTP响应代码,500(内部服务器错误),404(未找到)

public IHttpActionResult Get (int id) 
{ 
    Product product = _repository.Get (id); 
    if (product == null) 
    { 
     return NotFound(); // Returns a NotFoundResult 
    } 
    return Ok(product); // Returns an OkNegotiatedContentResult 
} 

有关此Action Results on Web Api 2的更多内容,您甚至可以编写自定义操作结果。

当应用程序客户端消耗时,它会得到正确的HTTP响应代码,任何响应对象或消息。