gpt4 book ai didi

c# - HttpClient PutAsync 不向 api 发送参数

转载 作者:太空狗 更新时间:2023-10-29 18:03:31 26 4
gpt4 key购买 nike

在 Controller 上Put如下:

[HttpPut]
[ActionName("putname")]
public JsonResult putname(string name)
{
var response = ...
return Json(response);
}

问题出在通过以下方式使用此 API 时

using (httpClient = new HttpClient())
{
string name = "abc";
string jsonString = JsonConvert.SerializeObject(name);
var requestUrl = new Uri("http:...../controller/putname/");
using (HttpContent httpContent = new StringContent(jsonString))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
}

此代码不会将参数名称传递给 Controller ​​。我什至尝试将 uri 更改为/putname/"+ name。

最佳答案

这是对我有用的:

var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent);
Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);

和我的操作方法:

public void PutRate(AppRating model)
{
if (model == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);

if (ModelState.IsValid)
{
// ..
}
}

和模型

public class AppRating
{
public int AppId { get; set; }
public int PlatformId { get; set; }
public decimal Rating { get; set; }
}

-斯坦

关于c# - HttpClient PutAsync 不向 api 发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10489611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com