将C#对象发送到web api控制器

时间:2013-10-26 19:23:28

标签: c# asp.net-web-api dotnet-httpclient

我正在尝试将C#对象传递给web api控制器。 api配置为存储发布到它的Product类型的对象。我已经使用Jquery Ajax方法成功添加了对象,现在我试图在C#中获得相同的结果。

我创建了一个简单的控制台应用程序来向api发送Post请求:

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" });

    }

永远不会调用postproduct方法,如何将此对象发送到控制器?

用于添加项目的方法:

    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 个答案:

答案 0 :(得分:16)

看起来你已经以某种方式禁止接受JSON作为发布格式。我能够将数据发送到您的终端并使用application/x-www-form-urlencoded创建新产品。这可能就是你的jQuery请求是如何做的。

您能否显示网络API的配置代码?您是否更改了默认格式化程序?

或者您可以从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();