Kun Li
Kun Li

Reputation: 111

How to read parameter from Request.Body in ASP.NET Core

Context: My application is behind a central login app, whenever the user apply access to my application, my application got a http request contain the user info. And I need to retrieve the user info from the HttpRequest Body.

This is what I tried so far:

currentContext.HttpContext.Request.Query["user-name"].toString();  // got nothing

using (var reader = new StreamReader(currentContext.HttpContext.Request.Body))
{
    var body = reader.ReadToEnd();
}   // I can get the raw HttpRequest Body as "user-name=some&user-email=something"

Is there any method I can use to parse the parameters and values from the Request.Body? I tried the following, got nothing either.

HttpContext.Item['user-name'] \\return nothing Request.Form["user-name"] \\ return nothing

and the reason I am not be able to use model binding is, in the HttpRequest body, the key name is "user-name", and in c#, I can't create a variable with a "-"

Meanwhile, in the my .net 4.6 application, Request["KeyName"].toString() works just fine.

Upvotes: 5

Views: 21515

Answers (2)

Kun Li
Kun Li

Reputation: 111

I figured out a way to convert the raw HttpRequest Body to a Query String, then read parameters from it.

Here is the code:

var queryString = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(requestBody);

string paramterValueIWant = queryString["KeyName"];

There is one problem though, when the KeyName doesn't exist in the body, it will throw an exception. So you have to null check or do a try catch.

Still I feel like there should be a better way to read the parameter, as I mentioned, in my .net 4.6 application, all I need to do is Request["KeyName"].

Upvotes: 6

Pietro di Caprio
Pietro di Caprio

Reputation: 152

Assuming that we are talking about POST/PUT/PATCH call, you can use
Request.Form["KeyName"] in your API method and set the 'contentType' of the Ajax request as application/x-www-form-urlencoded
Notice that Request is automagically available inside your method. No need to explicit call it.

When using GET/DELETE call i prefer to use

[HttpGet("{UserId}")] // api/User/{UserId}
public IActionResult Get(int UserId){
  // do stuff calling directly UserId
}

Or with PUT/PATCH

[Route("User/{EntityId}/{StatusFilter}")] // api/User/{EntityId}/{StatusFilter}
[HttpPut] 
public IActionResult Put(int EntityId, int StatusFilter){
  // do stuff calling directly EntityId and StatusFilter
}

where you can then still take data from the Body using Request.Form["KeyName"]

Upvotes: 3

Related Questions