ホームページ データベース 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 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

i7 3770に最適なグラフィックスカードは何ですか? i7 3770に最適なグラフィックスカードは何ですか? Dec 29, 2023 am 09:12 AM

Core 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 のインストールはお勧めできません。 uefi 起動の必要性と tpm2.0 の問題。 2. ただし、これはシステムでのアップデートのプッシュの取得を通常どおり制限するだけであり、pe システムを制限するものではありません。 3. したがって、USB フラッシュ ドライブを使用して win11 をダウンロードし、pe に win11 をインストールするだけです。 4. ただし、win11 を実行している場合、

Intel の最新プロセッサ i9-14900K は、Geekbench テストで際立っており、新世代のパフォーマンスをリードしています。 Intel の最新プロセッサ i9-14900K は、Geekbench テストで際立っており、新世代のパフォーマンスをリードしています。 Sep 22, 2023 pm 03:41 PM

9月6日のニュースによると、Intelは今月、新世代のRaptor Lake Refreshプロセッサシリーズを発売する予定だという。最新のニュースによると、このシリーズのフラッグシップ モデルである Core i9-14900K が、Geekbench6.1.0 シングルコア テストで素晴らしいパフォーマンスを示し、スコア 3121 を達成しました。前世代の 13900K と比較すると、この結果は約 6% 増加しました。マルチコアのパフォーマンスに関しては、前世代に比べてわずかに劣るものの、強力なコンピューティングの可能性も示しています。編集者の理解によれば、Core i9-14900K プロセッサーのパフォーマンスはその革新的な設計の恩恵を受けています。プロセッサーは 8 個の P コアと 16 個の E コアを使用し、マルチコア アーキテクチャを最大限に活用します。このプロセッサでは Th も導入されていることは特に言及する価値があります。

WebApi のクロスドメイン セカンダリ リクエストと Vue の単一ページの問題を Nginx がどのように解決するか WebApi のクロスドメイン セカンダリ リクエストと Vue の単一ページの問題を Nginx がどのように解決するか May 15, 2023 am 09:28 AM

1. はじめに プロジェクトがフロントエンドとバックエンドに分離されているため、API インターフェースと Web フロントエンドが別のサイトにデプロイされるため、前回の記事では、クロスドメインを使用した webapiajax クロスドメイン リクエスト ソリューション (cors 実装) を説明しました。 jsonpの代わりに処理します。しかし、しばらくすると、非常に奇妙な問題を発見しました。フロントエンドがリクエストを開始するたびに、ブラウザの開発者ツールを通じて、ネットワーク上に同じ URL に対する 2 つのリクエストがあることがわかります。最初の方法リクエストはオプションで、2 番目のリクエストのメソッドは実際の get または post で、最初のリクエストはデータを返さず、2 番目のリクエストは通常​​のデータを返します。 2. 最初のオプションの理由

i5 に win7 または win10 システムをインストールするのはどちらが良いですか? 詳細 i5 に win7 または win10 システムをインストールするのはどちらが良いですか? 詳細 Dec 23, 2023 pm 12:43 PM

コンピューターのプロセッサーが i5 プロセッサーであり、コンピューターのシステムを再インストールしたい場合、編集者は、システムのハードウェア構成要件に基づいて関連する考慮事項を行う必要があると考えます。 i5では?ハードウェア構成と個人的なニーズの点で自分に合ったものだけが最適です。詳しくは編集者のコメントを見てみましょう〜お役に立てれば幸いです。 i5 に win7 または win10 システムをインストールする方が良いですか? 回答: 今は i5 プロセッサに win10 システムをインストールする方が良いです。 1. win7 および win10 システムが現在ほとんどのユーザーによって使用されている限り、実際、2 つのシステムの構成要件は似ています。 2. したがって、パフォーマンス、流暢性、および適用性の点で、win10 システムは win7 よりも優れています。

i33240 は Windows 11 をサポートしてインストールできますか: 詳細分析 i33240 は Windows 11 をサポートしてインストールできますか: 詳細分析 Jan 03, 2024 am 10:34 AM

i33240 は非常に古典的な Intel プロセッサであり、基本的には古いコンピュータ モデルでもこの​​プロセッサが使用されています。したがって、Win11 がリリースされようとしている今、これらの古いデバイスのユーザーは、自分のコンピュータに Win11 システムをインストールできるかどうか知りませんが、一般的に言えば、それは可能です。 i33240 は win11 をインストールできますか: 回答: i33240 は win11 をインストールできますが、pe にインストールする必要があります。 1. Microsoft は以前、第 8 世代 Intel プロセッサ以降のみが win11 システムをインストールできると述べています。 2. ただし、実際には、この要件は Microsoft のシステム検出のみであり、インストール後の通常の使用には影響しません。 3. したがって、システム検出をスキップできる限り、次を使用できます。

WebApi のクロスドメイン セカンダリ リクエストと Vue の単一ページの問題を Nginx がどのように解決するか WebApi のクロスドメイン セカンダリ リクエストと Vue の単一ページの問題を Nginx がどのように解決するか May 22, 2023 pm 10:03 PM

1. はじめに プロジェクトがフロントエンドとバックエンドに分離されているため、API インターフェースと Web フロントエンドが別のサイトにデプロイされるため、前回の記事では、クロスドメインを使用した webapiajax クロスドメイン リクエスト ソリューション (cors 実装) を説明しました。 jsonpの代わりに処理します。しかし、しばらくすると、非常に奇妙な問題を発見しました。フロントエンドがリクエストを開始するたびに、ブラウザの開発者ツールを通じて、ネットワーク上に同じ URL に対する 2 つのリクエストがあることがわかります。最初の方法リクエストはオプションで、2 番目のリクエストのメソッドは実際の get または post で、最初のリクエストはデータを返さず、2 番目のリクエストは通常​​のデータを返します。 2. 最初のオプションの理由

Linux の実用的なヒントをいくつか確認してください Linux の実用的なヒントをいくつか確認してください Mar 12, 2024 pm 01:49 PM

Linux は、Linux をより効率的に使用するための便利なコマンドやヒントが数多く備わった強力なオペレーティング システムです。 1. ファイルチェック値を確認します ファイルのコピーまたは送信プロセス中に、ファイルが破損または変更されている可能性があります。この場合、チェック値を検証に使用できます。通常、私たちの作業では他のチームが提供するインターフェイス プログラムを使用する必要があります。これらのプログラムの実行結果が期待どおりにならない場合は、双方の md5 チェック値を比較してデータの一貫性を確認します。ファイルのチェック値を生成するにはさまざまな方法がありますが、一般的に使用される方法には、md5sum チェック、crc チェック、sum チェックなどが含まれます。コマンドは次のとおりです: md5sumfile_namecksumfile_namesum アルゴリズム パラメータ ファイル

See all articles