Akore
Akore

Reputation: 85

how to get content from httpContext c# dotnet

I'm trying to send post request to WebApi but cannot find httpContent in post method eventhough it's fine in Get Request

In WebApp

var json = JsonConvert.SerializeObject(new TestClass() { Id="someId"});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var res = await client.GetAsync("http://localhost:00000/home/testGet?username=" + username);
var post = await client.PostAsync("http://localhost:00000/home/testPost?username=" + username, content );

here is Post Request in WebApi (I want to bind the model as well)

public ActionResult testPost(string username)
{
    // username parameter is working
    // access HttpContent here
    var t = new TestClass() { Id = "333", Name = "name" };
    return Json(t, JsonRequestBehavior.AllowGet);
}

Content is transferd due to HttpContext.Request.ContentLength is varied depends on the json's Id I give to it.

Upvotes: 0

Views: 855

Answers (1)

SpruceMoose
SpruceMoose

Reputation: 10320

You may need to do something like this:

[HttpPost]
public ActionResult testPost([FromUri]string username, TestClass testClass)
{
    var t = new TestClass() { Id = "333", Name = "name" };
    return Json(t, JsonRequestBehavior.AllowGet);
}

Upvotes: 1

Related Questions