使用参数 C# 调用 HttpPut
本文关键字:调用 HttpPut 参数 | 更新日期: 2023-09-27 18:36:06
所以我在ASP.NET web api
中创建了一个HttpPut
方法。
[Route("api/Account/Save")]
[HttpPut]
public IHttpActionResult SaveAccount(Account acc) {
// do stuff
}
我一瞬间就通过了Account
课。
class Account
{
public int AccountID { get; set; }
public string AccountName { get; set; }
}
现在我想从控制台应用程序调用它。我正在尝试这样做,但它不起作用。它也没有抛出任何例外。
var acc = new Account() { AccountID = 1234, AccountName = "zzzzP" };
string json = JsonConvert.SerializeObject(acc);
HttpContent content = new StringContent(json);
response = await client.PutAsync("api/Account/Save", content);
杰森返回:
"{'"AccountID'":1234,'"AccountName'":'"zzzzP'"}"
你可能想要这样的东西
static async Task PutAccount()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourWebSite.com");
var acc = new Account() { AccountID = 1234, AccountName = "zzzzP" };
string json = JsonConvert.SerializeObject(acc);
using (HttpResponseMessage response = await client.PutAsync("api/Account/Save", new StringContent(json)))
{
return response.EnsureSuccessStatusCode();
}
}
}