简体   繁体   中英

Blazor - Multiple parameters routing (with comma) results in exception

Migrating an ASP.NET Core MVC web app to Blazor, I'm coming across a problem with routing. My current ASP.NET MVC routes seem to be impossible to replicate within @page directives.

An example URL: https://wows-karma.com/player/503379282,Akurai_Isayeki/

Routing in ASP.NET Core MVC was until now performed this way within the controller:

[Route("/{controller}/{id},{name}")]
public async Task<IActionResult> Profile(uint id) 
{
    // Controller Code
}

Here, only the Account ID is being used, and we ignore the following Username (you can even outright remove it, provided you leave the comma, and it should still work).

Now porting it to Blazor, I was hoping for an easy solution, like so:

@page "/player/{id},{name?}/"

// Page HTML

@code {
    [Parameter]
    public uint Id { get; set; }

    [Parameter]
    public string Name { get; set; } // We don't need it, and we'll ignore it.

    // Page Code
}

All seems well. But when comes runtime, Index throws this exception:

路由异常

(Be noted that I've tried other variations, such as with or without the slash, question mark on name and out of desperation, replaced the, for a - as a separation. No luck either)

My point now being, does Blazor routing support this edge case? I ask this, as I must STRICTLY follow this precise routing, to maintain URL compatibility with another website that is using the same scheme.

Now, I could use some Regex wizardry as a workaround, to mitigate the issue somewhat, but this could most likely cause more issues down the line, without actually ever directly solving the problem. So I'll only be using that if I'm left with no other choices. Let's just hope it doesn't come to that...

I don't think you can use that comma to separate parameters in Blazor routing.

Ideally your route would be something like:

@page "/player/{id}/{name}"

If you must retain compliance, I would go for

@page "/player/{idAndName}"

@code {
   [Parameter] public string idAndName { get; set; }

   protected override void OnParametersSet()
   {
        // Split the string property idAndName into the separate values you need.
   }
}

If you want to use non string route parameters you need need to use Route Constraints . However it appears in your case uint is not supported.

The .razor way is with two lines:

@page "/player/{id:int}"
@page "/player/{id:int}/{name}/"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM