c# - 从包含冒号 (:) 的查询参数名称中读取值
问题描述
我收到了在 .NET 应用程序中创建新 REST API 的请求,但我不知道如何实现其中一个参数。
我得到了一个 Swagger 定义,参数定义如下:
如果它eventCreatedDateTime=2021-04-01T14:12:56+01:00
没有问题,但它得到了冒号和等号之间的部分,我不知道如何得到。
基本上,我可以得到eventCreatedDateTime:gte=2021-04-01T14:12:56+01:00
一个查询字符串参数,我必须阅读该gte
部分并且还能够验证它是否是允许的后缀之一。后缀不是强制性的,因此eventCreatedDateTime=2021-04-01T14:12:56+01:00
也应该是有效的。
为澄清起见,这是一个查询字符串参数,因此是 URL 的一部分。例如https://example.com/api/mycontroller?param1=value¶m2=value&eventCreatedDateTime:gte=2021-04-01T14:12:56+01:00¶m4=value
知道如何在 .NET 中执行此操作吗?
解决方案
为此,我将使用自定义类型,例如:
public class EventCreatedDateTime
{
public string Operator { get; set; }
public string Value { get; set; }
}
接下来我将创建一个自定义模型绑定器:
public class EventCreatedDateTimeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if(context.Metadata.ModelType == typeof(EventCreatedDateTime))
{
return new EventCreatedDateTimeModelBinder();
}
return null;
}
}
public class EventCreatedDateTimeModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
foreach(var kvp in bindingContext.HttpContext.Request.Query)
{
if (kvp.Key.StartsWith("eventCreatedDateTime:"))
{
bindingContext.Result = ModelBindingResult.Success(
new EventCreatedDateTime {
Operator = kvp.Key.Substring("eventCreatedDateTime:".Length),
Value = kvp.Value.First()
});
}
}
return Task.CompletedTask;
}
}
我在 Startup 中添加:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
options.ModelBinderProviders.Insert(0, new EventCreatedDateTimeModelBinderProvider())
);
...
}
}
然后动作是:
[HttpGet]
public IActionResult Get(
string param1,
string param2,
EventCreatedDateTime eventCreatedDateTime)
{...}
推荐阅读
- python - 使用 map 和 zip 返回一个空数组
- javascript - 如何修复无效地址错误?带有 MetaMask 的 Web3 JS
- javascript - 为什么 .alert() 永久只显示相同的值?
- types - PyCharm 中的类型问题?
- python - 为什么 Mallet LDA 的结果很差,而 Gensim 版本却没有?
- mongodb - 无法连接到 rust 中的 MongoDB Atlas 数据库
- java - Java 可选与 C++ 可选
- spring-boot - 使用浏览器时如何使 Spring boot CSV 消息转换器显示 CSV 内联而不下载
- node.js - Node.js 集群仅用于 Express 应用程序中的特定功能
- r - 对具有缺失值的数据进行分组