简体   繁体   中英

How can I use HttpRequestMessage.CreateResponse<HttpError>() in ASP.NET 5

I have empty Web API project as well as full MVC project created using VS2015. I notice HttpRequestMessage is in System.Net.Http , thats fine but not for the CreateResponse below:

This code is from my exception logger middleware that also return formatted json from previous Web API 2.

var resp = request.CreateResponse<HttpError>(HttpStatusCode.InternalServerError, new HttpError("Internal Server Error. Reference: " + guid), config);

I am struggling to find out the CreateResponse extension method that supposedly available in System.Net.Http.HttpRequestMessageExtensions as well as HttpError class. Both previously in Microsoft.AspNet.WebApi.Core package.

After looking on ASP.NET 5 code, I believe it is only available in Microsoft.AspNet.Mvc.WebApiCompatShim . However it does not included in MVC sample project.

Questions:

What is WebApiCompatShim package and can I safely use it in the project?

What is the right way to CreateResponse from HttpRequestMessage ?

Update

This WebApiCompatShimWebSite shows that WebApiCompatShim is

to get Web API 2.* like behavior

So seems just for compatibility purpose. I have to restructure the code. Now I discover the MVC doesn't have any message handlers feature and seems custom middleware is the way to go.

If you add the NuGet Package Microsoft.AspNet.WebApi.Core , you will get the extensions you are looking for.

reference: https://www.nuget.org/packages/microsoft.aspnet.webapi.core/

That is an extension method of HttpRequestMessage class. You must reference to the below DLL which is included in Nuget Package Microsoft.AspNet.WebApi.Core :

Nuget\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll

This time you then can see CreateResponse method:

var response = request.CreateResponse(...)

According to:

https://docs.asp.net/en/latest/tutorials/first-web-api.html

You can achieve similar functionality by creating a new instance of ObjectResult (the status code can later be changed by setting the StatusCode property).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM