Receiving JSON object as a string in ASP.NET Core API
Just read from Request.Body
stream:
public async Task<IActionResult> ProcessPayment()
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
string rawValue = await reader.ReadToEndAsync();
}
...
}
Updated: the following doesn't work with ASP.NET Core 2.0.
Actually, the string
type for parameter should work if you post with Content-Type: application/json
:
public async Task<IActionResult> ProcessPayment([FromBody] string transaction)
{
...
}
There is a good article about all these things: Accepting Raw Request Body Content in ASP.NET Core API Controllers
Sam
Updated on June 06, 2022Comments
-
Sam almost 2 years
Is there a way for me to receive a
json
object as a string and not convert to a class in my Web API?If I create a class that matches the structure of the
json
object I receive, everything works nicely because theModelBinder
handles it. However, if I try to keep it as a string, it's failing. The value oftransaction
parameter ends up beingnull
-- see my API method below.This is what my
CreditCardTransaction
class looks like that I use to receive data into my API method:public class CreditCardTransaction { public int Amount { get; set; } public string Description { get; set; } public string Token { get; set; } // This is the json object }
And my API method looks like this:
[HttpPost("process")] public async Task<IActionResult> ProcessPayment([FromBody] CreditCardTransaction transaction) { if(transaction == null || !ModelState.IsValid) return new StatusCodeResult(400); // Process transaction }
I'm doing this for Stripe Checkout integration where Stripe frontend client converts sensitive credit card data into what they call a token which is a
json
object. So, in my backend API, I just want to receive the token along with a couple of simple data points i.e. amount and description.If I set my
CreditCardTransaction
class to the above structure,transaction
ends up getting anull
value. Looks likeModelBinder
doesn't like the idea of having ajson
object inToken
property which is defined as astring
.If I create a class that matches the structure of the
json
object for thetoken
, I'm able to receive it but it's causing other issues for me, not to mention all the unnecessary conversions.I do NOT need the
token
except to pass it to Stripe's API to complete the transaction. I will not save it or manipulate it. Looks like Stripe's API is expecting ajson
object anyway so I simply want to receive it and pass it to their API as is without messing with it.How do I receive this
json
object?