在 Razor Pages 中绑定查询参数的规则

Rules for binding query parameters in Razor Pages

在 Razor Pages 中,如果您调用

http://localhost/foo?bar=42

在相应的模型中,bar 键在 OnGet 构造函数中自动访问

public IActionResult OnGet(int bar)
{
    System.Console.WriteLine($"bar is {bar}");
}

但是如果查询参数是poo呢?

http://localhost/foo?poo=42

然后在模型中,bar 没有得到值 42。

如此简单,获取与查询参数键匹配的变量。但是,如果键被连字符怎么办?

http://localhost/foo?foo-bar=42

foo-bar 绝对不是可接受的变量名。如何访问此查询参数?这里的规则是什么?

在我的具体情况下,我别无选择,只能接收这些带连字符的查询字符串参数。另外,我在 .net core 2.2

Razor Pages 中最简单的解决方案是使用 Request.Query:

public void OnGet()
{
    var data = Request.Query["foo-bar"];
}

认为 heiphens 由下划线表示,因此 foo-bar 变为 foo_bar,但这违反了标准的 C# 命名约定。

无论如何我都不建议将查询参数绑定为处理程序参数。最干净的解决方案是在 PageModel 上定义一个 属性,如下所示:

// from the Microsoft.AspNetCore.Mvc namespace
[FromQuery(Name = "foo-bar")]
public string FooBar { get; set; }

这样,只要提供与该名称匹配的查询参数,它就会始终 被绑定。无论特定处理程序是否请求它。然后,您可以在需要时随时访问 PageModel 上的 属性。所以你的例子方法变成了:

public void OnGet()
{
    System.Console.WriteLine($"bar is {FooBar}");
}