찾다
데이터 베이스MySQL 튜토리얼IHttpActionResult(webAPI 2.0) instead of HttpResponseMessag

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으로 문의하세요.
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运行对于

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

英特尔最新处理器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

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、所以我们只要能够跳过系统检测,就可以使用

盘点一些Linux实用小技巧盘点一些Linux实用小技巧Mar 12, 2024 pm 01:49 PM

Linux是一个强大的操作系统,有许多实用的命令和技巧可以帮助你更高效地使用它。1、查看文件校验值在文件复制或传输过程中,可能会出现损坏或修改的情况,此时可以通过校验值来进行验证确认。通常,我们在工作中需要使用由其他团队提供的一些接口程序。每当这些程序的运行结果与预期不符时,我们会比对双方的md5校验值以确认数据的一致性。生成文件的校验值的方法有很多种,常用的有md5sum校验、crc校验、sum校验等。命令分别为:md5sumfile_namecksumfile_namesum算法参数file

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的

See all articles

핫 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 Hentai를 무료로 생성하십시오.

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구