使 [FromQuery] bool testValue 接受 'testValue', 'test_value' 和 'test-value'



ASP NET 6+中,我需要在匹配名称之前[FromQuery]替换下划线_和减号-

所以我想探测ASP以允许[FromQuery] bool testValue一次等效

  • [FromQuery(Name="testValue")] bool testValue
  • [FromQuery(Name="test-value")] bool testValue
  • [FromQuery(Name="test_value")] bool testValue

在比较名称之前,我可以进入管道中是否有一个位置(删除_-自己)

我当前的解决方案只是用我自己的篡改QueryCollection替换Request.Query,该在中间件中复制具有固定名称的变量。

但我正在寻找任何更多的答案...不骇人?!

public class RequeryMiddleware : IMiddleware
{
private static readonly char[] separators = new[] { '_', '-', '.', '|' };
private static bool Requery(ref string name)
{
bool changed = false;
if (name.IndexOfAny(separators) >= 0)
{
name = string.Concat(name.Split(separators, StringSplitOptions.None));
changed = true;
}
return changed;
}
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
Dictionary<string, StringValues> mods = new(
StringComparer.OrdinalIgnoreCase
);
foreach (var item in context.Request.Query)
{
string key = item.Key;
if (Requery(ref key))
{
mods.Add(key, item.Value);
}
}
if (mods.Count > 0)
{
Dictionary<string, StringValues> query = new(
context.Request.Query.Count + mods.Count
, StringComparer.OrdinalIgnoreCase
);
foreach (var item in context.Request.Query)
{
query.Add(item.Key, item.Value);
}
foreach (var mod in mods)
{
// if we get here it's bad...
query.TryAdd(mod.Key, mod.Value);
}
// replace the Query collection
context.Request.Query = new QueryCollection(query);
// change the QueryString too
QueryBuilder qb = new(context.Request.Query);
context.Request.QueryString = qb.ToQueryString();
}
return next(context);
}
}

最新更新