zoukankan      html  css  js  c++  java
  • Asp.Net WebApi接口返回值IHttpActionResult

    WebApi是微软在VS2012 MVC4版本中绑定发行的,webapi2.0同mvc5发行的

    webapi一共有以下接口返回值

    1、void无返回值
    2、IHttpActionResult

    • Json(T content)
    • Ok()、 Ok(T content)
    • NotFound()
    • 其他
    • 自定义IHttpActionResult接口的实现

    3、HttpResponseMessage
    4、自定义类型

    void无返回值

    没有返回值,http状态码204。我感觉用处不大,一个好的api应该有返回值。

    public class CeshiController : ApiController
    {
        public void PostSave()
        {
            //doing
        }
    }

    IHttpActionResult

    IHttpActionResult是Web API 2中引入的一个接口,IHttpActionResult是HttpResponseMessage的一个工厂类。IHttpActionResult是WebAPI中推荐的标准返回值,ApiController类中也提供了不少标准的工厂函数方便我们快速构建它们,如,Json,Ok,NotFound,BadRequest等。

    1、Json<T>(T content)

    比较常用的方法

    namespace cms.Web.API
    {
        public class CeshiController : ApiController
        {
            public studentBLL bll = new studentBLL();
            public IHttpActionResult GetList()
            {
                var list = bll.FindList();
                return Json(list);
            }
            public IHttpActionResult GetList2()
            {
                dynamic data = new { name = "李白", age = 20 };
                return Json(data);
            }
        }
    }

    2、Ok()、 Ok<T>(T content)

    比较常用的方法

    namespace cms.Web.API
    {
        public class CeshiController : ApiController
        {
            public studentBLL bll = new studentBLL();
            public IHttpActionResult GetList()
            {
                var list = bll.FindList();
                return Ok(list);
            }
            public IHttpActionResult GetList2()
            {
                dynamic data = new { name = "李白", age = 20 };
                return Ok(data);
            }
            public IHttpActionResult PostAdd()
            {
                //表示不向客户端返回任何信息,只告诉客户端请求成功
                return Ok();
            }
            public IHttpActionResult GetModel(int id)
            {
                var model = bll.Find(id);
                return Ok(model);
            }
        }
    }

    3、NotFound()

    比较常用的方法

    找不到记录时,有时需要用到NotFound()方法

            public IHttpActionResult GetModel(int id)
            {
                var model = bll.Find(id);
                if (model == null)
                {
                    return NotFound();
                }
                return Ok(model);
            }    

    4、其他返回值

    不常用

    Content<T>(HttpStatusCode statusCode, T value)

            public IHttpActionResult GetCeshi()
            {
                return Content(HttpStatusCode.OK, "hello webapi");
                //return Ok("hello webapi")//一样的效果
            }

    BadRequest()

            public IHttpActionResult GetCeshi(string name)
            {
                if (string.IsNullOrEmpty(name))
                {
                    return BadRequest();
                }
                return Ok();
            }

    Redirect(string location)

            public IHttpActionResult GetCeshi(string name)
            {
                return Redirect("https://www.cnblogs.com/webapi/");
            }

    HttpResponseMessage

    这个对象也有它独特的使用场景,需要向客户端返回HttpResponse时就要用到这个对象。以下载为例,由于需要将下载的文件输出到客户端浏览器,Webapi的服务端需要向Web的客户端输出文件流,这个时候一般的IHttpActionResult对象不方便解决这个问题,于是HttpReponseMessage派上了用场。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Web.Http;
    
    namespace cms.Web.API
    {
        public class CeshiController : ApiController
        {public HttpResponseMessage GetFile()
            {
                try
                {
                    var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/upload/ceshi.zip");
                    var stream = new FileStream(FilePath, FileMode.Open);
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StreamContent(stream);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "Wep Api Demo ceshi.zip"
                    };
                    return response;
                }
                catch
                {
                    return new HttpResponseMessage(HttpStatusCode.NoContent);
                }
            }
        }
    }

    自定义类型

    你可以将webapi的接口和普通方法一样,返回任意的类型,WebApi会自动序列化你自定义任何返回类型,然后将序列化的值写到响应正文里,状态码统一返回200。

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Web.Http;
    using cms.BLL;
    using cms.Model;
    
    namespace cms.Web.API
    {
        public class CeshiController : ApiController
        {
            public studentBLL bll = new studentBLL();
    
            public IEnumerable<student> GetList()
            {
                var list = bll.FindList();
                return list;
            }
    
            public student GetModel(int id)
            {
                var model = bll.Find(id);
                if (model == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return model;
            }
    
            public string GetMsg()
            {
                return "webapi";
            }
    
        }
    }

    // IHttpActionResult是WebAPI中微软官方推荐的标准返回值,建议大家使用这个,跟着微软走错不了。

  • 相关阅读:
    python中if __name__ == '__main__': 的解析
    python项目练习地址
    HTTP Response Splitting攻击探究 <转>
    常用操作系统扫描工具介绍
    app兼容性测试的几种方案
    svn自动备份并上传到ftp
    有关交易的性能测试点
    修改文件测试的测试点
    新增文件测试的测试点
    添加附件测试的测试点
  • 原文地址:https://www.cnblogs.com/webapi/p/10540916.html
Copyright © 2011-2022 走看看