Alim
Alim

Reputation: 337

WebApi HttpPost body content null

In my WebApi I have a HttpGet and HttpPost method, the get method is working fine and the post method is called but the body content is always null, unless used in a HttpRequestMessage. I tried providing the body content in a string format(preferred datatype) aswell as in a model but neither one of those methods worked. I also tried switching the content type without success. Does anyone know if I'm doing something wrong or how I can easily get the variable data from the HttpRequestMessage, which in the example below is "test".

Method 1:

[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem([FromBody]string filecontent, string companycode)
{
   MessageBox.Show(filecontent);

   Return Ok("");
}

Method 2 (with model):

[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem([FromBody]ItemXML filecontent, string companycode)
{
   MessageBox.Show(filecontent.XMLContent);

   Return Ok("");
}

Model:

public class ItemXML
{
  public ItemXML(string content)
  {
    XMLContent = content;
  }
  public string XMLContent { get; set; }      
}

Method 3:

[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem(HttpRequestMessage filecontent, string companycode)
{
   var content = filecontent.Content.ReadAsStringAsync().Result;    
   MessageBox.Show(content);

   Return Ok("");
}

Method 3 content string ("test" is the provided value): " content "------WebKitFormBoundarydu7BJizb50runvq0\r\nContent-Disposition: form-data; name=\"filecontent\"\r\n\r\n\"test\"\r\n------WebKitFormBoundarydu7BJizb50runvq0--\r\n" string"

Upvotes: 1

Views: 1195

Answers (1)

Nkosi
Nkosi

Reputation: 247098

Create a model store data to be sent to server

public class Model {
    public string filecontent { get; set;}
    public string companycode { get; set;}
}

Update Action

[HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem([FromBody]Model model) {
    if(ModelStat.IsValid) {
        return Ok(model); //...just for testing
    }
    return BadRequest();
}

On the client make sure the request is being sent properly. In this case going to use JSON.

public client = new HttpClient();

var model = new {
    filecontent = "Hello World",
    companycode = "test"
};

var response = await client.PostAsJsonAsync(url, model);

If using another type of client ensure that the data being sent is formatted correctly for the Web API action to accept the request.

Reference Parameter Binding in ASP.NET Web API

Upvotes: 1

Related Questions