使用webclient时,controller中的字符串参数为null

问题描述 投票:0回答:1

当我使用WebClient调用控制器中的函数时

using (WebClient client = new WebClient())
{
    client.BaseAddress = "http://localhost/";
    client.Headers.Add("Content-Type", "application/json");
    client.UploadString("api/test", HttpMethod.Put.ToString(), stringParameter);
}

我成功地在控制器中调用了该函数,但控制器中的“stringParameter”为空,如下面的代码:

[Route("api/test")]
[HttpPut]
public async Task<IHttpActionResult> Test([FromBody] string stringParameter)
{
    if (!ModelState.IsValid)
    {
        // the flow goes here
        return BadRequest(ModelState);
    }
    // ...
}

我想知道我犯的错误在哪里以及如何解决问题。非常感谢你。 备注:“stringParameter”如果是数字,如“123”则可以,但如果是“A123”或“B123”则不起作用。

c# webclient asp.net-apicontroller uploadstring
1个回答
1
投票

当您将内容类型设置为“application / json”时,您应该发送有效的JSON值而不是原始字符串。一个数字是JSON,在纯文本中是相同的,所以这就是它的工作原理。

在发送之前尝试将文本序列化为JSON:JsonConvert.ToString(stringParameter);(我在这里使用Newtonsoft.Json nuget包)

或者你可以尝试使用内容类型text/plain,但我不确定你的web api是否配置为默认处理。

© www.soinside.com 2019 - 2024. All rights reserved.