Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ASP.NET Core equivalent to HttpRequestMessage?

I found a blog post that shows how POSTed JSON can be received as a string.

I want to know what's the new native way to do the same thing as the following code in a REST Post method in a Controller:

public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
    var jsonString = await request.Content.ReadAsStringAsync();

    // Do something with the string 

    return new HttpResponseMessage(HttpStatusCode.Created);
}

The other option bellow does not work for me, i think because I don't use Content-Type: application/json in the request header (can't change this), and I get a 415 .

public HttpResponseMessage Post([FromBody]JToken jsonbody)
{
    // Process the jsonbody 

    return new HttpResponseMessage(HttpStatusCode.Created);
}
like image 507
Gerald Hughes Avatar asked Aug 08 '17 12:08

Gerald Hughes


People also ask

Does net5 replace NET Core?

Net 5 that is Opensource and Cross-platform, which will replace . Net Framework, . Net Core and Xamarin with a single unified platform called . Net 5 Framework.

Is .NET Core and MVC core same?

The main difference between ASP.NET Core and ASP.NET MVC 5 is their cross-platform approach. ASP.NET Core can be used on Windows, Mac, or Linux, whereas ASP.NET MVC 5 can only be used for applications on Windows. The ASP.NET Core MVC is a framework for building web apps and APIs, optimized for use with ASP.NET Core.

What is HttpRequestMessage?

The HttpRequestMessage class contains headers, the HTTP verb, and potentially data. This class is commonly used by developers who need additional control over HTTP requests. Common examples include the following: To examine the underlying SSL/TLS transport information. To use a less-common HTTP method.

How do I register IHttpClientFactory in .NET Core?

Using Named HttpClient Instances In the Program class, we use the AddHttpClient method to register IHttpClientFactory without additional configuration. This means that every HttpClient instance we create with the CreateClient method will have the same configuration.


1 Answers

In .Net Core they have merged the Web API and MVC so you could just do it like this with IActionResult or one of its derivatives.

public IActionResult Post([FromBody]JToken jsonbody)
{
    // Process the jsonbody 

    return Created("", null);// pass the url and the object if you want to return them back or you could just leave the url empty and pass a null object
}
like image 111
npo Avatar answered Oct 22 '22 11:10

npo