Home Database Mysql Tutorial 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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the best graphics card for i7 3770? What is the best graphics card for i7 3770? Dec 29, 2023 am 09:12 AM

What graphics card is good for Core i73770? RTX3070 is a very powerful graphics card with excellent performance and advanced technology. Whether you're playing games, rendering graphics, or performing machine learning, the RTX3070 can handle it with ease. It uses NVIDIA's Ampere architecture, has 5888 CUDA cores and 8GB of GDDR6 memory, which can provide a smooth gaming experience and high-quality graphics effects. RTX3070 also supports ray tracing technology, which can present realistic light and shadow effects. All in all, the RTX3070 is a powerful and advanced graphics card suitable for those who pursue high performance and high quality. RTX3070 is an NVIDIA series graphics card. Powered by 2nd generation NVID

Can the i7 generation be installed with win11? Can the i7 generation be installed with win11? Dec 30, 2023 pm 11:40 PM

As we all know, there are device restrictions on the installation of win11, and restrictions such as uefi startup are set on the CPU. So can the earliest i7 generation install win11? In fact, it is theoretically possible, but installation is not recommended. Can the i7 generation be installed with win11: Answer: The i7 generation can be installed with win11, but if the configuration is too low, it will freeze, so it is not recommended to install win11. 1. Win11 limits the CPU mainly due to the need for uefi startup and tpm2.0 issues. 2. But this will only restrict us from getting update push in the system normally, and will not restrict the PE system. 3. So we only need to use a USB flash drive to download win11 and install win11 in pe. 4. However, when running win11,

Intel's latest processor i9-14900K stands out in the Geekbench test, leading the new generation in performance! Intel's latest processor i9-14900K stands out in the Geekbench test, leading the new generation in performance! Sep 22, 2023 pm 03:41 PM

According to news on September 6, Intel will launch a new generation of Raptor Lake Refresh processor series this month. The latest news shows that the flagship model of this series, the Core i9-14900K, performed brilliantly in the Geekbench6.1.0 single-core test, achieving a score of 3121. Compared with the previous generation of 13900K, this result has increased by about 6%. In terms of multi-core performance, although it is slightly inferior to the previous generation, it also shows strong computing potential. According to the editor's understanding, the performance of the Core i9-14900K processor benefits from its innovative design. The processor uses 8 P cores and 16 E cores, taking full advantage of the multi-core architecture. It is particularly worth mentioning that this processor also introduces Th

How Nginx solves the problem of WebApi cross-domain secondary requests and Vue single page How Nginx solves the problem of WebApi cross-domain secondary requests and Vue single page May 15, 2023 am 09:28 AM

1. Introduction Since the project is separated from the front and back ends, the api interface and the web front end are deployed in different sites, so in the previous article, the webapiajax cross-domain request solution (cors implementation) uses cross-domain processing instead of jsonp. But after a period of time, I discovered a very strange problem. Every time the front end initiates a request, through the browser's developer tools, I can see that there are two requests for the same URL under the network. The method of the first request is options, the method of the second request is the real get or post, and the first request returns no data, and the second request returns normal data. 2. Reason for the first options

Is it better to install win7 or win10 system on i5? Details Is it better to install win7 or win10 system on i5? Details Dec 23, 2023 pm 12:43 PM

If the processor of our computer is an i5 processor, and we want to reinstall the system of the computer, the editor thinks that we should make relevant considerations based on the hardware configuration requirements of the system. Is it better to install win7 or win10 system on i5? . Only the one that suits you in terms of hardware configuration and personal needs is the best. Let’s take a look at what the editor said for details~ I hope it can help you. Is it better to install win7 or win10 system on i5? Answer: It is better to install win10 system on i5 processor now. 1. As far as win7 and win10 systems are currently used by the most users, in fact, the configuration requirements of the two systems are similar. 2. Therefore, in terms of performance, fluency, and applicability, the win10 system is better than win7

Can i33240 support and install Windows 11: Detailed analysis Can i33240 support and install Windows 11: Detailed analysis Jan 03, 2024 am 10:34 AM

i33240 is a very classic Intel processor. Basically, older computer models still use this processor. Therefore, now that Win11 is about to be launched, these old device users do not know whether their computers can install the Win11 system. Generally speaking, it is possible. Let’s take a look at it together. Can i33240 install win11: Answer: i33240 can install win11, but it must be installed in pe. 1. Although Microsoft has previously stated that only eighth-generation Intel processors and above can install the win11 system. 2. But in fact, this requirement is only Microsoft's system detection, and it will not affect normal use after installation. 3. So as long as we can skip system detection, we can use

How Nginx solves the problem of WebApi cross-domain secondary requests and Vue single page How Nginx solves the problem of WebApi cross-domain secondary requests and Vue single page May 22, 2023 pm 10:03 PM

1. Introduction Since the project is separated from the front and back ends, the api interface and the web front end are deployed in different sites, so in the previous article, the webapiajax cross-domain request solution (cors implementation) uses cross-domain processing instead of jsonp. But after a period of time, I discovered a very strange problem. Every time the front end initiates a request, through the browser's developer tools, I can see that there are two requests for the same URL under the network. The method of the first request is options, the method of the second request is the real get or post, and the first request returns no data, and the second request returns normal data. 2. Reason for the first options

Take stock of some practical Linux tips Take stock of some practical Linux tips Mar 12, 2024 pm 01:49 PM

Linux is a powerful operating system with many useful commands and tips to help you use it more efficiently. 1. Check the file check value. During the file copying or transmission process, the file may be damaged or modified. In this case, the check value can be used for verification. Usually, we need to use some interface programs provided by other teams in our work. Whenever the running results of these programs are not as expected, we will compare the md5 check values ​​of both parties to confirm the consistency of the data. There are many ways to generate the check value of a file. Commonly used ones include md5sum check, crc check, sum check, etc. The commands are: md5sumfile_namecksumfile_namesum algorithm parameter file

See all articles