日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

【Web API系列教程】1.2 — Web API 2中的Action Results

發布時間:2023/11/27 生活经验 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Web API系列教程】1.2 — Web API 2中的Action Results 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

本節的主題是ASP.NET Web API怎樣將控制器動作的返回值轉換成HTTP的響應消息。

Web API控制器動作能夠返回下列的不論什么值:
1。 void
2。 HttpResponseMessage
3, IHttpActionResult
4, Some other type

取決于返回的以上哪一種。Web API使用不同的機制來創建HTTP響應。

Return typeHow Web API creates the response
voidReturn empty 204 (No Content)
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).

本節的剩余部分將具體描寫敘述每種返回值。

void

假設返回類型是type,Web API就會用狀態碼204(No Content)返回一個空HTTP響應。

演示樣例控制器:

public class ValuesController : ApiController
{public void Post(){}
}

HTTP對應:

HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 02:13:26 GMT

HttpResponseMessage

假設一個動作返回HttpResponseMessage,Web API就通過HttpResponseMessage的屬性構造成消息從而直接將返回值轉換成HTTP響應。

public class ValuesController : ApiController
{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)};return response;} 
}

對應:

HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMThello

假設傳遞一個域模型給CreateResponse方法。Web API會使用媒體格式(media formatter)將序列化模型寫入到響應體中。

public HttpResponseMessage Get()
{// Get a list of products from a database.IEnumerable<Product> products = GetProductsFromDB();// Write the list to the response body.HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);return response;
}

IHttpActionResult

IHttpActionResult接口在Web API 2中被引進。本質上,它定義了一個HttpResponseMessage工廠。下面是使用IHttpActionResult接口的優點:
1, 簡單你的控制器的單元測試
2。 為創建HTTP對應將公共邏輯移動到單獨的類
3。 通過隱藏構建對應的底層細節。使控制器動作更清晰

IHttpActionResult包括一個單獨的方法ExecuteAsync。它會異步地創建一個HttpResponseMessage實例:

public interface IHttpActionResult
{Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
} 

假設一個控制器動作返回IHttpActionResult,Web API會調用ExecuteAsync方法來創建HttpResponseMessage。然后將HttpResponseMessage轉換到HTTP對應消息里。

下面是一個IHttpActionResult的簡單運行,它創建一個文本對應:

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);}
}

控制器動作演示樣例:

public class ValuesController : ApiController
{public IHttpActionResult Get(){return new TextResult("hello", Request);}
}

對應:

HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMThello

更通常的情況是,你會使用System.Web.Http.Results命名空間下定義的IHttpActionResult實現。

在接下來的演示樣例中,假設請求沒有匹配到不論什么已存在的產品ID。控制器就會調用ApiController.NotFound來創建一個404(Not Found)響應。否則,控制器會調用ApiController.OK,它會調用一個意為包括該產品的200(OK)對應。

public IHttpActionResult Get (int id)
{Product product = _repository.Get (id);if (product == null){return NotFound(); // Returns a NotFoundResult}return Ok(product);  // Returns an OkNegotiatedContentResult
}

Other Return Types

對于其它全部返回類型。Web API使用媒體格式(media formatter)來序列化返回值。

Web API將序列化值寫入到響應體中。響應狀態碼是200(OK)。

public class ProductsController : ApiController
{public IEnumerable<Product> Get(){return GetAllProductsFromDB();}
}

該實現的缺點在于你不能直接返回一個錯誤碼,比方404。

Web API通過在請求中使用Accept頭來選擇格式。

演示樣例請求:

GET http://localhost/api/products HTTP/1.1
User-Agent: Fiddler
Host: localhost:24127
Accept: application/json

演示樣例對應:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
Content-Length: 56[{"Id":1,"Name":"Yo-yo","Category":"Toys","Price":6.95}]

轉載于:https://www.cnblogs.com/brucemengbm/p/7250132.html

總結

以上是生活随笔為你收集整理的【Web API系列教程】1.2 — Web API 2中的Action Results的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。