Winforms调用Web API时出现HTTP错误400

9gm1akwq  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(220)

我正在使用Visual Studio 2022开发一个Winforms程序,Visual Studio在调用Web API时报告了一个http 400错误。
代码如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request. Referer = Referer;

byte[] bytes = Encoding.UTF8.GetBytes(Data);

request.ContentType = "application/json";
request.ContentLength = bytes.Length;

Stream myResponseStream = request.GetRequestStream();

myResponseStream.Write(bytes, 0, bytes.Length);

HttpWebResponse response = (HttpWebResponse) request.GetResponse(); //error

错误:
System.Net.WebException:“远程服务器返回错误:(400)错误的请求。
这是我的Web API控制器:

[Route("api/MyWebApi")]
 [ApiController]
 public class MyWebApiController : ControllerBase
 {
     private readonly ILogger<MyWebApiController> _logger;

     public MyWebApiController(ILogger<MyWebApiController> logger)
     {
         _logger = logger;
     }

     [HttpPost("[action]")]
     public IActionResult SayHello([FromBody] UserModel model)
     {
         if (model.pwd != "1")
         {
             object obj = new
             {
                 code = "0",
                 msg = "Request failed"
             };

             return new JsonResult(obj);
             //return new BadRequestResult();
         }
         else
         {
             object obj = new
             {
                 code = "1",
                 msg = "Request successful"
             };

             return new JsonResult(obj);
         }
     }
 }

我试了这个ASP.NET Web Api HttpResponseException 400 (Bad Request) Hijacked by IIS,它似乎不工作。有人能帮助我吗?

wqlqzqxt

wqlqzqxt1#

因为我注意到你的ContentType是application/json,那么在传递数据的时候就不能使用string或者int,需要保持数据类型的一致性,可以参考How to Turn a C# Object Into a JSON String in .NET

相关问题