13

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;
    }
3
  • Your code seems fine, what do you see in fiddler? Have you enabled webapi tracing on the server? Commented Oct 26, 2013 at 19:50
  • I can see requests that originate from a form that I'm using no requests sent by the HttpClient are visible in Fiddler. I've also uploaded the api to: producttestapi.azurewebsites.net/api/products but none of the requests from the HttpClient reach that api either. Commented Oct 26, 2013 at 20:13
  • also, check the index.html of that url, thats the form I use to send objects through ajax, that one works so the api is ok. Commented Oct 26, 2013 at 20:15

1 Answer 1

17

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();
Sign up to request clarification or add additional context in comments.

3 Comments

the ajax method has 'dataType: "json"' defined. So that leads me to think that the controller still accepts JSON as data. I added the method that handles adding new objects to the list. I would show the configuration code, is it a .cs file from the App_Start folder? Meanwhile, going to try the approuch you posted here.
I was able to use the PostAsJson method also using the code you gave and now it works. Thank you very much, sir!
What we can do if we have a parameter like string array in the class. I can't set it to the Dictionary since FormUrlEncodedContent is not accepting Dictionary<string, Object>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.