我希望在 C# 中也能在 C# 中调用 ApiController,但在使用 WebClient 实例的 UploadString 方法上传 Json 时出现错误 415 或 400。
服务器代码是自动生成的调用TestController。该文件正是 Visual Studio 2019 生成它的方式。
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// POST: api/Test
[HttpPost]
public void Post([FromBody] string value)
{
}
...
}
客户端代码如下所示:
WebClient client = new WebClient();
client.UploadString("https://localhost:44345/api/Test", "ABC"); // Edit: "ABC" is not a valid JSON
我得到 System.Net.WebException:“远程服务器返回错误:(415) 不支持的媒体类型。”
所以在谷歌搜索之后,大多数建议是 ContentType 没有得到指定,如果我添加
client.Headers[HttpRequestHeader.ContentType] = "application/json";
我收到 System.Net.WebException:“远程服务器返回错误:(400) 错误请求。”
有什么线索吗?
似乎问题与POST
/PUT
/PATCH
有关...如果我执行GET
,它正在运行并返回示例数据 ["value1","value2"]
编辑:我不坚持使用 WebClient.UploadString 方法,但我想要一个不涉及 25 行自定义代码的解决方案......我的意思是我不敢相信你可以做到这一点在 jQuery 中使用单行。
最佳答案
I'm getting System.Net.WebException: 'The remote server returned an error: (415) Unsupported Media Type.'
当您使用[FromBody]
时,Content-Type
header 用于确定如何解析请求正文。当未指定 Content-Type
时,模型绑定(bind)进程不知道如何使用正文,因此返回 415。
I get System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'
通过将 Content-Type
header 设置为 application/json
,您指示模型绑定(bind)过程将数据视为 JSON,但 ABC
本身不是有效的 JSON。如果您只想发送一个 JSON 编码的字符串,您也可以将值用引号引起来,如下所示:
client.UploadString("https://localhost:44345/api/Test", "\"ABC\"");
“ABC”
是一个有效的 JSON 字符串,将被您的 ASP.NET Core API 接受。
关于C# WebClient 使用 UploadString 从同样在 C# 中的 ApiController 调用 HttpPost 方法。 415 或 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55853572/