'ASP.NET Core 6 MVC web app - default action for root url

I have an ASP.NET Core 6 MVC web project. I want to have an action that fires when the root of the site is hit with a parameter.

For example: https://example.com/123abc

Note: 123abc could be any 6-character alphanumeric text.

I want it to hit my controller action like this:

public IActionResult DefaultAction(string param)

So in the example above, when that Url is called, DefaultAction gets hit and the value of param is '123abc'

Another example would be: https://example.com/test55

// here param = "test55"
public IActionResult DefaultAction(string param) 

Any help or advice on making this work would be appreciated!



Solution 1:[1]

You can add information like Default Controller and default action methods in StartUp.cs of your MVC project. In StartUp.cs class, there are two default methods:

  1. ConfigureServices Method: Where you can register your services
  2. Configure Method: Where you can define your middlewares like routing, authentication, authorization, etc.

In Configure method, you can use the below code to mention your default controller and default action method like this:

app.UseEndpoints(endpoints =>
{
  endpoints.MapControllerRoute(
     name: "default",
     pattern: "{controller=Home}/{action=DefaultAction}/{param?}"
  );
});

In here, "Home" is default controller and "DefaultAction" is default method

Solution 2:[2]

You can have default controller for your project. And normally without mentioning anything Index action of default controller gets hit. But since you have a parameter it may confuse it with an action name. And also parameter in url should have name unless it's id. I guess if you rename param to id it should work. However above solution is the clean solution.

Solution 3:[3]

Use the regular expressions in constraints.

See detailed description in the documentation: Regular expressions in constraints

[Route("/{param:regex(^([[a-zA-Z0-9]]{{6}})$)}")]
public IActionResult DefaultAction(string param)

The regular expression tokens explanation:

Token Explanation
^ Asserts position at start of a line
[a-zA-Z0-9] Matches any character in the range a-z, A-Z or 0-9
{6} Sequence must contain exactly 6 characters
$ Asserts position at the end of a line

Pay attention: to escape routing parameter delimiter characters {, }, [, ], double the characters in the expression, for example, {{, }}, [[, ]].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vivek Kosare
Solution 2 Danial Kalhori
Solution 3