如何读取和迭代HTTPGET参数



我正在用.Net Core做一个简单的后端,它从GET和POST中读取数据,但我找不到如何读取GET params和POST。我有一个简单的控制器:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
[HttpGet]
public string Get()
{
return "Test GET OK";
}
[HttpPost]
public string Post()
{
return "Test POST OK";
}
}

Client是一个简单的windows表单,使用net框架4.6,使用HttpClient发送http get请求:

public async Task<string> GetAsyncHttpClient(string uri)
{
string responseBody = "";
try
{
UriBuilder builder = new UriBuilder(uri);
builder.Query = "name=testName";
HttpResponseMessage response = await client.GetAsync(builder.Uri);
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
}
catch (Exception e)
{
Console.WriteLine("nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
responseBody = "Error with GET operation, exception:n" + e.ToString();
}
return responseBody;
}

生成的URL是这样的:

http://localhost:5915/test?name=testName

相信我,我已经搜索了很多,但没有找到如何读取和迭代GET参数。我该怎么做?

谢谢!

通常情况下,您只需在方法中添加一个参数:

[HttpGet]
public string Get(string name)

您可以明确表示它是一个查询字符串参数,如下所示:

[HttpGet]
public string Get([FromQuery]string name)

至于迭代参数,您必须使用Request.Query:

foreach (KeyValuePair<string, StringValues> entry in Request.Query)
{
string key = entry.Key;
foreach (string value in entry.Value)
{
System.Diagnostics.Debug.WriteLine($"{key}={value}");
}
}

您需要为StringValues添加一个using Microsoft.Extensions.Primitives;。它之所以是StringValues,是因为你可以有一个这样的URL:https://www.example.com/test?name=Brian&name=Jennifer,所以你最终会在Query集合条目中有两个"的值;名称";。

我不知道你的确切意思,但如果你只是想发布帖子或获得请求,那么你可以在你的客户中这样做:

using (var client = new HttpClient())
{
try
{
HttpResponseMessage response =
await client.PostAsync("https://localhost:YOURPORT/Test?username=test", YOURCONTENT);
var cont = await response.Content.ReadAsStringAsync();
Console.WriteLine(cont);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.ReadKey();
}

确保您使用的是http或https,因此您必须调整url以及

如果您指的是查询参数,您可以通过将其添加到API来访问它们:

[HttpPost]
public void Post([FromQuery] string username){
//do something
}

最新更新