我有一个 Blazor 服务器应用程序。它使用 ASP.NET 身份库,即 ASP.NET Core MVC。我正在尝试传递一个参数来登录,因此像
/identity/account/Register?follow=uniqueId
这样的 URL 会为我提供参数 follow=uniqueId
。
在
Register.cshtml.cs
(班级RegisterModel
)我有:
public async Task OnGetAsync(string returnUrl = null, string following = null)
{
ReturnUrl = returnUrl;
Following = following;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null, string following = null)
{
// ...
}
来自 url 的值被传入
OnGetAsync()
就好了。但是当 OnPostAsync() is called, it passes in a null for
followingand the object property
Following` 也为 null 时。
如何在
OnPostAsync()
中获取该参数?
有道理。因为后端希望将这些值作为 url 中的参数。您始终可以将
[FromBody]
属性添加到控制器中的参数中。但它对于简单的类型来说却很时髦。
示例:
public async Task<IActionResult> OnPostAsync([FromBody] string returnUrl = null, [FromBody] string following = null)
{
...
}
我建议将数据包装到一个对象中,比方说:
public class MyData
{
public string ReturnUrl { get; set; }
public string Following { get; set; }
}
然后将您的发布方法修改为:
public async Task<IActionResult> OnPostAsync([FromBody] MyData myData)
{
...
}
此修改的缺点是您需要修改前端以将字符串包装为
MyData
格式。
有关 ASP.NET 中参数绑定的其他信息: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api