WebAPI 返回值

关于webapi的返回值有下面这几种:

1.void:我有返回值,这里不做解释,只要能够调用正确的方法便能够正确的执行。

2.IHttpActionResult:Json,Ok,NotFound,Contentm,Redirect等返回值,推荐使用这个。

3.HttpResponseMessage

4.自定义,这个也不讲解,相当于直接return。

关于IHttpActionResult返回数据

使用json返回数据

public class LoginController : ApiController
    {
        public IHttpActionResult IHAR()
        {
            var l_EntityData = new { id = 1, name = "namejr", age = 12 };
            return Json(l_EntityData);  // json()
            //return Json<实体>(l_EntityData);  // json<T>()
        }
    }

使用OK返回数据

public class LoginController : ApiController
    {
        public IHttpActionResult IHAR()
        {
            var l_EntityData = new { id = 1, name = "namejr", age = 12 };
            return Ok(l_EntityData);  // json()
            //return Ok();  // json()表示只返回成功提示,不返回消息
            //return Ok<实体>(l_EntityData);  // json<T>()
        }
    }

使用notfound()来返回找不到结果

public IHttpActionResult IHAR()
        {
            var l_EntityData = new { id = 1, name = "namejr", age = 12 };
            if(l_EntityData==null)
            {
                return NotFound();  // 用来返回找不到记录
            }
            return Ok(l_EntityData);  // json()
            //return Ok();  // json()表示只返回成功提示,不返回消息
            //return Ok<实体>(l_EntityData);  // json<T>()
        }

使用Reddirect来跳转页面

public class LoginController : ApiController
    {
        public IHttpActionResult IHAR()
        {
            return Redirect("http://www.baidu.com");  // 用来跳转页面
        }
    }

 使用HttpResponseMessage进行返回响应信息

[HttpGet]
        public HttpResponseMessage InputFile()
        {
            try
            {
                string l_strFilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Script/swagger.js");  // 获取路径
                FileStream l_streamFileStream = new FileStream(l_strFilePath, FileMode.Open);  // 打开文件
                // 构建HttpResponseMessage返回响应信息
                HttpResponseMessage l_response = new HttpResponseMessage(HttpStatusCode.OK);
                l_response.Content = new StreamContent(l_streamFileStream);//l_response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  // 构建contenttype,如果这句话存在,会访问出错(仅使用postman进行测试过,其他的没测过,应该是构建类型错误)
                l_response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")  // 构建描述
                {
                    FileName = "Web Api Demo"
                };
                return l_response;  // 返回响应信息
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound);  // 返回找不到响应
            }
        }

详细了解,请看:https://www.cnblogs.com/webapi/p/10540916.html

原文地址:https://www.cnblogs.com/namejr/p/11619611.html