Sending C# object to webapi controller

2019-02-12 17:17发布

I'm trying to pass a C# object to a web api controller. The api is configured to store objects of type Product that are posted to it. I have successfully added objects using Jquery Ajax method and now I'm trying to get the same result in C#.

I've created a simple Console application to send a Post request to the api:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

         static void Main(string[] args)
    {
        string apiUrl = @"http://localhost:3393/api/products";
        var client = new HttpClient();
        client.PostAsJsonAsync<Product>(apiUrl, new Product() { Id = 2, Name = "Jeans", Price = 200, Category =  "Clothing" });

    }

The postproduct method is never invoked, how to send this object to the controller ?

Method used for adding items:

    public HttpResponseMessage PostProduct([FromBody]Product item)
    {
        item = repository.Add(item);
        var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);

        string uri = Url.Link("DefaultApi", new { id = item.Id });
        response.Headers.Location = new Uri(uri);
        return response;
    }

1条回答
乱世女痞
2楼-- · 2019-02-12 17:35

Looks like you have somehow disabled accepting JSON as format for posting. I was able to send the data to your endpoint and create new product using application/x-www-form-urlencoded. That is probably how your jQuery request is doing it.

Can you show your configuration code of your web api? Do you change the default formatters?

Or you could send a form from HttpClient. e.g.

    string apiUrl = "http://producttestapi.azurewebsites.net/api/products";
    var client = new HttpClient();
    var values = new Dictionary<string, string>()
        {
            {"Id", "6"},
            {"Name", "Skis"},
            {"Price", "100"},
            {"Category", "Sports"}
        };
    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync(apiUrl, content);
    response.EnsureSuccessStatusCode();
查看更多
登录 后发表回答