简体   繁体   中英

WebApi - why is my post variable always null?

I'd like to be able to read a post variable from my controller method.

I currently have the below code:

[HttpPost]
public IHttpActionResult BuildPartitions([FromBody]string PartitionBuildDate)
{
}

I'm using the below code to test:

using (HttpClient httpClient = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
        { "PartitionBuildDate", "24-May-2017" }
    };
    var content = new FormUrlEncodedContent(values);
    var response = httpClient.PostAsync("http://localhost:55974/api/Controller/BuildPartitions", content);
    var responseString = response.Result.Content;
}

Looking online, this looks correct for both sending and receiving a post variable in C#, however the PartitionBuildDate variable is always null.

Try adding the content-type header. I have used Newtonsoft JSON.NET for JSON conversion:

string postBody = JsonConvert.SerializeObject(yourDictionary);

var response = client.PostAsync(url, new StringContent(postBody, Encoding.UTF8, "application/json"));

var responseString = response.Result.Content;

Also, on your web API side, try wrapping your POST parameters inside a class:

public class PostParameters
{
    public string PartitionBuildDate {get;set;}
}

[HttpPost]
public IHttpActionResult BuildPartitions([FromBody]PostParameters parameters)
{
    //you can access parameters.PartitionBuildDate
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM