gpt4 book ai didi

c# - MVC API 在正文中发送数据

转载 作者:行者123 更新时间:2023-12-03 08:29:01 26 4
gpt4 key购买 nike

我正在尝试将数据发送到使用 Postman 可以正常工作的 API,但我不确定如何在代码中执行此操作。

我创建了这个使用测试 json 字符串的方法,它发送正文中的数据。当我调试它时,错误来自这一行

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

我收到消息

The remote server returned an error: (400) Bad Request.'"

任何帮助都会很大,不确定我做错了什么。

public static T Post<T>(string httpMethod, string url, object model)
{
var fullUrl = apiUrl + url;

var json = "{\"FirstName\":\"1\",\"LastName\":\"1\"}";


string data = json;

Stream dataStream = null;
WebRequest Webrequest;
Webrequest = WebRequest.Create(fullUrl);


Webrequest.ContentType = "application/json";
Webrequest.Method = WebRequestMethods.Http.Post;

Webrequest.PreAuthenticate = true;
Webrequest.Headers.Add("Authorization", "Bearer Toeke n");

byte[] byteArray = Encoding.UTF8.GetBytes(data);

Webrequest.ContentLength = byteArray.Length;

dataStream = Webrequest.GetRequestStream();

using (dataStream = Webrequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}

WebResponse response = Webrequest.GetResponse();
}

API

 [HttpPost]
public IHttpActionResult SaveForm(RequestWeb Request)

postman 原始

{
"FirstName": "1",
"LastName": "1",
}

最佳答案

您使用 WebRequest 而不是 HttpClient 有什么具体原因吗?如果您不执行任何 FTP 工作并且使用 .NET Framework 4.5+.NET Core,那么最好迁移到 HttpClient 因为它为您提供了更轻松的使用流程,提供开箱即用的异步支持,并且更容易模拟和测试,同时为您提供更多功能。总的来说,它是用于从 .NET 发出请求的现代 API。

public async Task<T> Post<T>(object model) // use actual model type instead of type object
{
var url = "Specify URL";
var token = "Specify Token";

var payload = JsonSerializer.Serialize(model);

// Preferably get the instance from dependency injection or hoist it as a private variable in the class body.
// In any case, don't recreate it like we're doing here.
var client = new HttpClient();

var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);

requestMessage.Headers.Add("Authorization", $"Bearer {token}");
requestMessage.Content = new StringContent(payload, Encoding.UTF8, "application/json");

var responseMessage = await client.SendAsync(requestMessage);

if (responseMessage.IsSuccessStatusCode)
{
var result = await responseMessage.Content.ReadAsStringAsync();

return JsonSerializer.Deserialize<T>(result);
}
else
{
// Handle error result
throw new Exception();
}
}

关于c# - MVC API 在正文中发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65705062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com