我一直在做一些关于如何通过API调用从c#中的URL获取查询字符串参数的研究,我找不到任何相关信息。我找到了一堆关于如何在PHP中做到这一点的资源,但这不是我使用的。
我也不知道我是否必须设置端点来接受查询字符串参数作为调用的一部分,但我相信我这样做。
我所有的Restful API目前都在URL路径上工作,所以我想通过后端解析的所有内容都与/
分开,我不希望这样。我想通过查询字符串解析处理的所有信息,并使用/
只解析特定的路径位置。
这是我的端点当前的设置方式。
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "api/v1/{controller}/{id?}/{id1?}/{id2?}/{id3?}/{id4?}/{id5?}/{id6?}");
});
这是一个API调用
[HttpGet("/api/v1/Templates/{customerId}")]
public List<string> GetTemplates(string customerId)
{
return templatesService.GetTemplates(customerId);
}
我想解析我的客户ID为http://localhost:0000/api/v1?customerId=1
带有额外参数的示例:
[HttpPost("/api/v1/Templates/{customerId}/{templateName}/{singleOptions}/{multiOptions}")]
public string GetReplacedTemplate(string customerId, string templateName, string singleOptions, string multiOptions)
{
return templatesService.GetReplacedTempalte(customerId, templateName, singleOptions, multiOptions);
}
所以这里我有两个额外的参数是SingleOptions
和MultiOptions
。主控制器为Templates
。
我认为即使TemplateName
也应该被解析为查询,因为我觉得它的额外参数也是。
这不是一个需要解决的问题,因为使用/
来分离每个参数工作得很好,但我真的想知道如何解析查询字符串。
我通常不回答我自己的问题,但这里是供其他人查看。
在c#中通过API调用获取Query字符串参数实际上很容易。
在你的参数上使用[FromQuery]
数据绑定将允许你接受你解析它的内容:)
[HttpGet("/api/v1/Templates")]
public string GetTemplatesQuery([FromQuery] string customerId)
{
return customerId;
}