将 C# 对象发送到 webapi 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19610883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:24:42  来源:igfitidea点击:

Sending C# object to webapi controller

c#asp.net-web-apidotnet-httpclient

提问by neo112

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#.

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

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

我创建了一个简单的控制台应用程序来向 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" });

    }

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

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

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

采纳答案by Darrel Miller

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.

看起来您以某种方式禁止接受 JSON 作为发布格式。我能够将数据发送到您的端点并使用application/x-www-form-urlencoded. 这可能是您的 jQuery 请求正在执行的操作。

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

你能显示你的 web api 的配置代码吗?您是否更改默认格式化程序?

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

或者您可以从 HttpClient 发送表单。例如

    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();