【发布时间】: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