HttpClient via BSON to RESTful API

Viewed 738

I have tried post object from window client to a controller.

It can be receive Test Object but id and id2 is 0 and null value.

Did I miss some config?

public class Test
{
    public int id { get; set; }
    public string id2 { get; set; }
}

//webapiconfig

public static void Register(HttpConfiguration config)
{

    config.MapHttpAttributeRoutes();
    config.Formatters.Add(new BsonMediaTypeFormatter());
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

window client

private async void Form1_LoadAsync(object sender, EventArgs e)
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:58716/");

        // Set the Accept header for BSON.
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

        var aa = new Test()
        {
            id = 2,
            id2="3333"
        };

        // POST using the BSON formatter.
        MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
        var result = await client.PostAsync("Report/Test", aa, bsonFormatter);
        result.EnsureSuccessStatusCode();
    }

}

web server

public class ReportController : Controller
{
    public void Test(Test aa)
    {

    }
}
1 Answers

Register is configuring for a ApiController while the shown ReportController is a MVC Controller

Update Target controller to derive from the correct type and have the necessary attributes.

[RoutePrefix("api/Report")]
public class ReportController : ApiController {
    //POST api/Report/Test
    [HttpPost]
    [Route("Test")]
    public IHttpActionResult Test([FromBody]Test model) {
        if(ModelState.IsValid) {
            //...

            return Ok();
        }
        return BasRequest(ModelState);
    }
}

And update the client to send to the correct URL

//...

 // POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var result = await client.PostAsync("api/Report/Test", aa, bsonFormatter);
result.EnsureSuccessStatusCode();
Related