zoukankan      html  css  js  c++  java
  • WebAPI Action的几种返回值类型

    void 返回204状态码
    HttpResponseMessage Convert directly to an HTTP response message.
    IHttpActionResult Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
    Other type Write the serialized return value into the response body; return 200 (OK).

    1. void 返回204状态码

            public void Get()
            {
    
            }

    2.直接转化成http响应消息

    public HttpResponseMessage Get()
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("hello", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromMinutes(20)
        };
      //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new { a=1,b=2});
      //return response;
    return response;

    3.IHttpActionResult  调用 ExecuteAsync 创建HttpResponseMessage,最后实现 public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)方法

    常用类https://msdn.microsoft.com/en-us/library/system.web.http.results(v=vs.118).aspx,也可以自定义实现IHttpActionResult接口。

     public IHttpActionResult Get()
            {
                return NotFound();//Ok()
                //return new TextResult("hello", Request);
    
            }
           
    
        }
        public class TextResult : IHttpActionResult
        {
            string _value;
            HttpRequestMessage _request;
    
            public TextResult(string value, HttpRequestMessage request)
            {
                _value = value;
                _request = request;
            }
            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                var response = new HttpResponseMessage()
                {
                    Content = new StringContent(_value),
                    RequestMessage = _request
                };
                
                return Task.FromResult(response);
            }
        }

    4.使用其他类型

    public Product Get()
            {
                return new Product { Id = 1, Name = "我的商品" };
            }
    
        }
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

     如果上述出现异常,无法返回404错误码,可以使用过滤器标签处理。

    本文参考:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results

  • 相关阅读:
    LINUX怎么远程连接ORACLE数据库
    Debian 6配置GNOME桌面环境
    简简单单安装debian桌面工作环境
    NeHe OpenGL教程 第四课:旋转
    NeHe OpenGL教程 第三课:颜色渲染
    NeHe OpenGL教程 第二课:多边形
    NeHe OpenGL教程 第一课:OpenGL窗口
    Oracle数据库 External component has thrown an exception
    9. Ext基础1 -- Ext中 getDom、get、getCmp的区别
    8. Ext文本输入框:Ext.form.TextField属性汇总
  • 原文地址:https://www.cnblogs.com/lzhp/p/5198486.html
Copyright © 2011-2022 走看看