WebAPI Action的几种返回值类型

 2023-09-16 阅读 16 评论 0

摘要:void返回204状态码HttpResponseMessageConvert directly to an HTTP response message.IHttpActionResultCallExecuteAsyncto create anHttpResponseMessage, then convert to an HTTP response message.Other typeWrite the serialized return value into the response body;
void返回204状态码
HttpResponseMessageConvert directly to an HTTP response message.
IHttpActionResultCall ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Other typeWrite the serialized return value into the response body; return 200 (OK).

1. void 返回204状态码

        public void Get(){}

java后端返回数据有几种方式、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;

 

接口返回json数据格式,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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/70053.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息