首页 > 解决方案 > 从包含冒号 (:) 的查询参数名称中读取值

问题描述

我收到了在 .NET 应用程序中创建新 REST API 的请求,但我不知道如何实现其中一个参数。

我得到了一个 Swagger 定义,参数定义如下:

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&param2=value&eventCreatedDateTime:gte=2021-04-01T14:12:56+01:00&param4=value

知道如何在 .NET 中执行此操作吗?

标签: c#.netrestasp.net-web-api

解决方案


为此,我将使用自定义类型,例如:

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)
{...}

推荐阅读