Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the serialized JSON in WebAPI

How do I get access to the JSON from a controller method in a WebApi? For example below I want access to both the de-serialized customer passed in as a parameter, and the serialized customer.

public HttpResponseMessage PostCustomer(Customer customer)
{
    if (ModelState.IsValid)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = customer.Id }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }
like image 298
Noel Avatar asked Jun 06 '26 12:06

Noel


1 Answers

You will not be able to get the JSON in controller. In ASP.NET Web API pipeline, binding happens before the action method executes. Media formatter would have read the request body JSON (which is a read-once stream) and emptied the contents by the time the execution comes to your action method. But if you read the JSON from a component running in the pipeline before the binding, say a message handler, you will be able to read it like this. If you must get the JSON in action method, you can store it in the properties dictionary.

public class MessageContentReadingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
                                  HttpRequestMessage request,
                                      CancellationToken cancellationToken)
    {
        var content = await request.Content.ReadAsStringAsync();

        // At this point 'content' variable has the raw message body
        request.Properties["json"] = content;

        return await base.SendAsync(request, cancellationToken);
    }
}

From the action method, you can retrieve JSON string like this:

public HttpResponseMessage PostCustomer(Customer customer)
{
    string json = (string)Request.Properties["json"];
}
like image 57
Badri Avatar answered Jun 08 '26 02:06

Badri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!