Bercovici Adrian
Bercovici Adrian

Reputation: 9360

How to retrieve POST data in Controller

I am trying to POST a value to ASP NET Core Controller. The Controller keeps getting a null value and i do not understand why.

Sending request

 string uri = "/api/create";
//some POCO--not important 
  CampaignRequest<CreateCampaignParams> req = new 
  CampaignRequest<CreateCampaignParams> { Data = campaignParams, Ticket = this.ticket };

  var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8, "application/json");
  var response = await this.http.PostAsync(uri, content);

Receiver

   [HttpPost]
   [Route("api/create")]
   public async Task<long> CreateAsync([FromBody]CampaignRequest<CreateCampaignParams>pars)
   {
    //--- the received argument is null...i have tried putting as a string argument to no avail
      try
      {
        var client = new CampaignClient(uri,pars.Ticket.Value);
        long rez=await client.CreateCampaignAsync(pars.Data);
        return rez;   
      }
      catch (Exception)
      {
        return 0;
      }
}

I have tried setting the parameter of the Controller method as string ,and then deserialize it.Still the string was empty.
How do you retrieve a StringContent in a controller?

Upvotes: 0

Views: 97

Answers (1)

Flores
Flores

Reputation: 8942

The most likely cause is a model binding error.

To check for this, modify your controller method like so:

[HttpPost]
[Route("api/create")]
public async Task<long> CreateAsync([FromBody]CampaignRequest<CreateCampaignParams> pars)
{
     var errorCount = ModelState.ErrorCount;

And set a breakpoint on that errorCount line, if the count is > 0 then futher examine the ModelState object for the specific errors.

Also, are you sure that your POST request is correctly adding your object in the body using the F12 browser tools. Please include a screenshot of that if not sure.

Upvotes: 1

Related Questions