MVC 将 url 参数传递给 POST

问题描述 投票:0回答:1

我有一个 Blazor 服务器应用程序。它使用 ASP.NET Identity Library,即 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 
following
and the object property
Following` 也为 null 时。

如何在

OnPostAsync()
中获取该参数?

asp.net-mvc asp.net-identity
1个回答
0
投票

有道理。因为后端希望将这些值作为 url 中的参数。您始终可以将

[FromBody]
属性添加到控制器中的参数中。但它对于简单的类型来说却很时髦。

我建议将数据包装到一个对象中,比方说:

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

© www.soinside.com 2019 - 2024. All rights reserved.