How to post a string to WEB API

How to post a string to WEB API? 

It is tricky because the client may post the string and specify content-type to some value.

Below is the cleanest way I can come up with:

[AcceptVerbs("POST")]
public HttpResponseMessage ActionA()
{
string content = this.ControllerContext.Request.Content.ReadAsStringAsync().Result;
}

Here is another way:

public RespMessage Post(HttpRequestMessage request)
{
string content = this.ControllerContext.Request.Content.ReadAsStringAsync().Result;

Yet another way:

public RespMessage ActionA([FromBody]string value)
{
// read the posted string from the request.Content
string content = this.ControllerContext.Request.Content.ReadAsStringAsync().Result;
}

The official way is a bit tricky on the client.

public RespMessage ActionA([FromBody]string value)
{
// posted string is stored in “value”
}

If you want to have “value” populated with the posted string, the client needs to specify

Content-Type: application/x-www-form-urlencoded

And the request body needs to have a “=” prefix.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s