【问题标题】:Adding a json body to a POST with WebRequest使用 WebRequest 将 json 正文添加到 POST
【发布时间】:2021-11-04 09:00:29
【问题描述】:

我正在尝试通过正文发布一些项目,但我不断收到 “(400)错误请求”据我所知,这通常是您尝试访问的端点的问题。 这是正确的,因为我已经通过简单的调用对其进行了测试。

这是我第一次尝试以这种方式使用身体进行 POST,所以我不确定我错过了什么或做错了什么。

这是我要达到的端点

[Route("api/[controller]")]
   [ApiController]
   public class SaleController : ControllerBase
   {
       [HttpPost]
       [Route("[action]")]
       [Route("Sale/Test")]
       public string Test([FromBody] Inventory[] inventories)
       {
           return "Found me";
       }
}

它会在 httpResponse 中弹出 err 400


   public IEnumerable<Inventory> GetTest(IpPartial ipPartial, Inventory[] inventories)
        {
            WebRequest request = WebRequest.Create("http://localhost:5002/api/Sale/Test");
            request.Method = "POST";
            request.ContentType = "application/json";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string jsonString = new JavaScriptSerializer().Serialize(inventories);

                streamWriter.Write(jsonString);
                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    var pass = result.ToString();
                }
                streamWriter.Flush();
                streamWriter.Close();
            }

            return inventories;
        }

这只是我想要传递的一个简化的想法

[
    {
        "id": 1,
        "categoryId": 1,
        "taxId": 1,
        "unitId": 1,
        "scheduleId": 0,
        "description": "Konsultasie",
        "code": ""
    },
    {
        "id": 2,
        "categoryId": 7,
        "taxId": 1,
        "unitId": 1,
        "scheduleId": 10,
        "description": "Laxapet 50g",
        "code": "220L"     
    }
]

【问题讨论】:

  • WebRequest 及其同类已过时且已死。他们在.net 墓地。请改用IHttpClientFactory。您会发现它们对现代功能更加友好,因此涉及它们的问题将获得更多答案

标签: c# asp.net webrequest


【解决方案1】:

只需切换到一个简单的异步调用即可解决。

public async Task<IEnumerable<Inventory>> CreateSale(IpPartial ipPartial, Inventory[] inventories)
        {
            string jsonString = new JavaScriptSerializer().Serialize(inventories);
            var data = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var url = "http://localhost:5002/api/Sale/CreateSales";
            using var client = new HttpClient();
            var response = await client.PostAsync(url, data);
            string result = response.Content.ReadAsStringAsync().Result;

            return inventories;
            
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2012-06-25
    • 2022-08-16
    • 2016-01-23
    • 2021-09-12
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多