I have a Blazor Server app. It uses the ASP.NET Identity Library which is ASP.NET Core MVC. I am trying to pass a parameter to login so a URL like /identity/account/Register?follow=uniqueId
gives me the parameter follow=uniqueId
.
In Register.cshtml.cs
(class RegisterModel
) I have:
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)
{
// ...
}
The value from the url is passed in to OnGetAsync()
fine. But when OnPostAsync() is called, it passes in a null for
followingand the object property
Following` is also null.
How do I get that parameter in OnPostAsync()
?
Make sense. Because backend expect to have these values as parameters in url. You always can add [FromBody]
attribute to the parameters in your controller. But it works funky with simple types.
Example:
public async Task<IActionResult> OnPostAsync([FromBody] string returnUrl = null, [FromBody] string following = null)
{
...
}
I would recommend to wrap your data into an object, let’s say:
public class MyData
{
public string ReturnUrl { get; set; }
public string Following { get; set; }
}
Then modify your post method to:
public async Task<IActionResult> OnPostAsync([FromBody] MyData myData)
{
...
}
Downside of this modification is that you need to modify your front-end to wrap your strings into MyData
format.
Additional information about parameter binding in ASP.NET:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api