neo*_*112 10 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" });
}
Run Code Online (Sandbox Code Playgroud)
永远不会调用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;
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*ler 16
看起来你已经以某种方式禁止接受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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37031 次 |
| 最近记录: |