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

2023-11-21

我正在尝试将 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;
    }

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

你能展示一下你的 web api 的配置代码吗?您更改默认格式化程序吗?

或者您可以从 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 C# 对象发送到 webapi 控制器 的相关文章