gpt4 book ai didi

c# - 将数据从字符串值发布到 asp net core web api Controller 方法

转载 作者:行者123 更新时间:2023-11-30 21:33:38 25 4
gpt4 key购买 nike

我有一个带有 REST Controller 的 Asp Net Core 2.1 应用程序:

[Produces("application/json")]
[Route("api/Test")]
public class TestController : Controller
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }

// GET: api/Test/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id) { return "value"; }

// POST: api/Test
[HttpPost]
public void Post([FromBody]string value)
{
//.. testing code..
}

// PUT: api/Test/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value) {}

// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id) {}
}

我正在尝试使用“System.Net.HttpWebRequest”对象向 Rest Controller 发出 POST 请求。在我的客户端应用程序中,我有一个以字符串形式接收数据的方法。
字符串内容是一个动态值数组,例如“param1=value1;param2=value2”(元素数量是可变的)。
你能帮我理解将这些数据发送到 Controller 的正确方法吗?

这是我试图在客户端中使用的代码:

public static string PostWebApi(string postData)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost:64817/api/test");

// for example, assumes that postData value is "param1=value1;param2=value2"
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded";

request.ContentLength = data.Length;

using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

return responseString;
}

我正在使用内容类型“application/json”:如果我尝试使用“application/x-www-form-urlencoded”,我会收到“(415) 不支持的媒体类型”错误。
所以...当我执行 PostWebApi 时,我在 POST: api/Test 方法中收到一个 Null 值参数。
我怎样才能收到我发送的数据?

提前致谢。

最佳答案

您可以为此使用 HTTPClient。它会为您简化流程。

public static string PostWebApi(string postData)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64817/api/test");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value", postData)
});
var result = await client.PostAsync("/api/Membership/exists", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}

引用:- How to make HTTP POST web request

关于c# - 将数据从字符串值发布到 asp net core web api Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134041/

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