首頁 資料庫 mysql教程 IHttpActionResult(webAPI 2.0) instead of HttpResponseMessag

IHttpActionResult(webAPI 2.0) instead of HttpResponseMessag

Jun 07, 2016 pm 03:48 PM
i webapi

Hi all, I hope everyone is fine, me too. I am being amazed day by day by seeing new features and improvements to MVC from Microsoft. If you have had hands-on experience with MVC and the Web API then you are very familiar with HTTP response

Hi all, I hope everyone is fine, me too. I am being amazed day by day by seeing new features and improvements to MVC from Microsoft. If you have had hands-on experience with MVC and the Web API then you are very familiar with HTTP responses from the Web API.

If we remember the HTTP response creation of Web API 1.0 we used to use write 3 to 4 lines of code to create one full fledge HTTP response by setting the status code and media type with an appropriate message. The style is something like this.

  1. var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);  
  2. var tsc = new TaskCompletionSource();  
  3. tsc.SetResult(response);  
  4. return tsc.Task;  
This code snippet will return one Unauthorized HTTP response (haha.. not an unauthorized response, but HTTP response of unauthorized type) asynchronously. Now, if we want to change the response type then obviously we must change the status code.

Fine and simple but it is simpler in the Web API 2. We can create the same kind of response with a single line of code. 

Here you will see how the ASP.NET Web API converts the return value from a controller into an HTTP response message. 

Please note that the feature is available in Web API 2.0, so please ensure that your application is updated to 2.0 versions before trying the following code. We know that a Web API controller action can return any one of the following.

 

  • Void
  • HttpResponseMessage
  • IHttpActionResult (new in Web API 2.0)
  • Some other data type

Now in today's article we will see the third point with an example. To use IHttpResult in your application, you must include “System.WebHttp” and provide a reference of the “system.Web.Http” assembly. 

The interface IHttpActionResult contains one any only one method called “ExecuteAsync”. Here is the definition of the interface:

  1. public interface IHttpActionResult  
  2. {  
  3.    Task ExecuteAsync(CancellationToken cancellationToken);  
  4. }  
Fine, now let's see how to return a HTTP Response from the controller with a single line of code using the interface. Have a look at the following example.

  1. public class personController : ApiController  
  2. {  
  3.    public IHttpActionResult Get()  
  4.    {  
  5.       return Ok();  
  6.    }  
  7.   
  8. }  
Here I have implemented a small empty person controller and defined a Get() within it. The Get() method is again empty and returning only Ok and this is the key point of the example. We know that Ok or success is one status type of HTTP and it's code is 200.

So, when we are returning Ok from a controller/action then the Web API runtime engine is transfers the Ok to a full fledge response message by setting the status code 200 with it. Let's see how it works practically. We will call the action from the client and we will check whether or not it returns an Ok response message. Here is the output from Fiddler.

 

IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

And we are seeing that the status code is 200 and type is OK. So, now just think how simple it is to create a HTTP response from Web API 2.0.

Ok, you may think, how to embed some value with the HTTP response message? Fine, the next example is for you.

  1. public class personController : ApiController  
  2. {  
  3.    public IHttpActionResult Get()  
  4.    {  
  5.       return Okstring> ("I am send by HTTP resonse");  
  6.    }  
  7.   
  8. }  
We are just returning string a in the message body and the output in Fiddler is something like this.

 

IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

Please look that, the response string is coming as a body of HTTP response. Not only string, we can send any complex type of custom data type as a body of the HTTP response message. In the next example we will try to send a list of strings in the body of the response message with an Ok status. Here is our modified code.

  1. public IHttpActionResult Get()  
  2. {  
  3.     Liststring> names = new Liststring> {   
  4.        "Sourav",  
  5.        "Ram"  
  6.     };  
  7.     return Okstring>> (names);  
  8. }  
And the output is in JSON format.


IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

Fine, so we have seen how easy it is to create an Ok HTTP response message in the Web API, just by a single line of code. Not only an Ok message, but we can also return any type of valid HTTP response, let's see a few of them.

Not Found

  1. public IHttpActionResult Get()  
  2. {  
  3.    return NotFound();  
  4. }  
Like Ok() , we can return NotFound() , it will return a 404 status code as in the following screen.

IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

Bad Request

  1. public IHttpActionResult Get()  
  2. {  
  3.    return BadRequest();  
  4. }  
We know the status code for BadRequest is 400 and once we call the method, we will get the status.

IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

Unauthorized

In the same way, we can return an unauthorized status code, here is sample code.

  1. public IHttpActionResult Get()  
  2. {  
  3.    return Unauthorized();  
  4. }  
IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

Created


The status code for the Created status is 201 and generally the status is returned when the Post() operation is performed successfully. Created takes two parameters, one is the “uri” and the other is content.

IHttpActionResult(webAPI 2.0)  instead of HttpResponseMessag

Conclusion

In this article we have discussed how to send a HTTP response message with a minimal amount of code. I Hope you have understood this and like it. Happy learning.







http://stackoverflow.com/questions/20903420/how-to-call-asp-net-mvc-webapi-2-method-properly

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

i7 3770的最佳搭配顯示卡是什麼? i7 3770的最佳搭配顯示卡是什麼? Dec 29, 2023 am 09:12 AM

酷睿i73770配什麼顯卡好啊RTX3070是一款非常強大的顯示卡,它具有出色的性能和先進的技術。無論是玩遊戲、渲染圖形或是進行機器學習,RTX3070都能輕鬆應付。它採用了NVIDIA的Ampere架構,擁有5888個CUDA核心和8GB的GDDR6內存,能夠提供流暢的遊戲體驗和高品質的圖形效果。 RTX3070也支援光線追蹤技術,能夠呈現逼真的光影效果。總而言之,RTX3070是一款強大且先進的顯示卡,適合那些追求高效能和高品質的使用者使用。 RTX3070是一款NVIDIA系列的顯示卡。採用第2代NVID

i7世代可以裝win11嗎 i7世代可以裝win11嗎 Dec 30, 2023 pm 11:40 PM

眾所周知win11的安裝是有設備限制的,還對cpu設定了uefi啟動等限制,那麼最早的i7一代可以裝win11嗎,其實理論上是可以的,不過不建議安裝。 i7世代可以裝win11嗎:答:i7世代可以裝win11,但如果設定太低會卡頓,所以其實不建議安裝win11。1、win11限制cpu主要是因為需要uefi啟動和tpm2.0問題。 2.但這只會限制我們正常在系統中取得更新推送,並不會限制pe系統。 3.所以我們只要使用u盤下載win11,在pe中安裝win11就可以了。 4.不過win11運行對於

英特爾最新處理器i9-14900K在Geekbench測試中脫穎而出,性能領先新一代! 英特爾最新處理器i9-14900K在Geekbench測試中脫穎而出,性能領先新一代! Sep 22, 2023 pm 03:41 PM

9月6日消息,英特爾即將在本月推出全新一代RaptorLakeRefresh處理器系列。最新消息顯示,這一系列的旗艦型號酷睿i9-14900K在Geekbench6.1.0單核測試中表現亮眼,取得了3121的成績。與上一代的13900K相比,這一成績提升了約6%。而在多核心效能方面,雖然稍稍不及上一代,但也展現了強大的運算潛力。據小編了解,酷睿i9-14900K處理器的效能得益於其創新性的設計。處理器採用了8個P核心和16個E核心,充分發揮了多核心架構的優勢。特別值得一提的是,該處理器還引入了Th

Nginx如何解決WebApi跨域二次請求及Vue單頁的問題 Nginx如何解決WebApi跨域二次請求及Vue單頁的問題 May 15, 2023 am 09:28 AM

一、前言由於專案是前後端分離,api介面與web前端部署在不同站點當中,因此在前文當中webapiajax跨域請求解決方法(cors實作)使用跨域處理方式處理而不用jsonp的方式。但在一段時間後,發現一個很奇怪的問題,每次前端發起請求的時候,透過瀏覽器的開發者工具都能看到在network下同一個url有兩個請求,第一條請求的method為options,第二條請求的method才是真正的get或post,並且,第一條請求無資料返回,第二條請求才返回正常的資料。二、原因第一個options的

i5裝win7好還是win10系統好詳情 i5裝win7好還是win10系統好詳情 Dec 23, 2023 pm 12:43 PM

我們的電腦如果處理器是i5處理器的話,想要對於電腦進行系統重裝的話,對於i5裝win7好還是win10系統好這個問題小編覺得我們還是要根據系統的硬體配置要求來進行相關的考量。只有在硬體配置以及個人需求上適合自己的才是最好的。詳細內容就來看下小編是怎麼說的吧~希望可以幫助到你。 i5裝win7好還是win10系統答:i5處理器現在裝win10系統比較好。 1.就目前使用者最多的win7還有win10系統來說,其實兩者的設定需求都是差不多的。 2.因此在性能、流暢度、適用性方面來看,win10系統比起win7

i33240能否支援並安裝Windows 11:詳細解析 i33240能否支援並安裝Windows 11:詳細解析 Jan 03, 2024 am 10:34 AM

i33240是一款非常經典的英特爾處理器,現在還是使用這款處理器的基本上都是比較老的電腦型號。因此現在win11即將推出,這些老設備用戶不清楚自己的電腦不知道能否安裝win11系統,一般來說都是可以的,下面就一起來看一下吧。 i33240能裝win11嗎:答:i33240可以安裝win11,但必須在pe中安裝。 1.雖然微軟先前表示只有第八代以上的英特爾處理器可以安裝win11系統。 2.但其實這個要求只是微軟的系統偵測,安裝完後並不會影響到正常的使用。 3.所以我們只要能夠跳過系統偵測,就可以使用

Nginx怎麼解決WebApi跨域二次請求及Vue單頁的問題 Nginx怎麼解決WebApi跨域二次請求及Vue單頁的問題 May 22, 2023 pm 10:03 PM

一、前言由於專案是前後端分離,api介面與web前端部署在不同站點當中,因此在前文當中webapiajax跨域請求解決方法(cors實作)使用跨域處理方式處理而不用jsonp的方式。但在一段時間後,發現一個很奇怪的問題,每次前端發起請求的時候,透過瀏覽器的開發者工具都能看到在network下同一個url有兩個請求,第一條請求的method為options,第二條請求的method才是真正的get或post,並且,第一條請求無資料返回,第二條請求才返回正常的資料。二、原因第一個options的

盤點一些Linux實用小技巧 盤點一些Linux實用小技巧 Mar 12, 2024 pm 01:49 PM

Linux是一個強大的作業系統,有許多實用的指令​​和技巧可以幫助你更有效率地使用它。 1.查看檔案校驗值在檔案複製或傳輸過程中,可能會出現損壞或修改的情況,此時可以透過校驗值來進行驗證確認。通常,我們在工作中需要使用由其他團隊提供的一些介面程式。每當這些程式的運作結果與預期不符時,我們會比對雙方的md5校驗值以確認資料的一致性。產生檔案的校驗值的方法有很多種,常用的有md5sum校驗、crc校驗、sum校驗等。指令分別為:md5sumfile_namecksumfile_namesum演算法參數file

See all articles