【问题标题】:How to deal with the result that i wanted in asp.net web api如何处理我在 asp.net web api 中想要的结果
【发布时间】:2015-10-15 16:37:35
【问题描述】:

我正在尝试为应用程序开发人员编写 web api,我想要下面的示例 api 结果

当异常时:

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

正常:json 字符串中的 Result 是 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 帮助页面中看到返回类型的详细信息。

实现起来容易吗?怎么做(没有细节,只是逻辑,细节更好。)

谢谢大家!

【问题讨论】:

  • 返回该对象作为结果return this.Ok(yourObject);
  • @Fabio 那么返回类型与方法声明不匹配,对吧?那么合适的返回类型是什么?
  • 返回类型将是 IHttpActionResult 并且在客户端 Result 值可以基于 StatusCode 使用
  • 返回类型为IHttpActionResult时,api helper生成的api文档看不到类型声明详情。

标签: asp.net asp.net-web-api2 asp.net-web-api


【解决方案1】:

您应该创建 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 }
        );
    }
}

无需更改和添加控制器。

【讨论】:

  • 如果我的回答有帮助,请标记为正确
【解决方案2】:

使用 IHttpActionResult 会非常有帮助,尤其是如果您考虑的是应用程序开发人员。它非常适用于 200(Ok)、500(Internal Server Error)、404(Not Found) 等 Http 响应代码

这是一个简单的代码示例,您在其中获取产品并根据返回返回适当的响应

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 响应代码、任何响应对象或消息。

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2015-09-26
    相关资源
    最近更新 更多