In an ASP.NET Core MVC project, how do I change the URL for Razor pages from the default format like http://localhost:5088/Home/Faq
, to a specific URL such as
http://localhost:5088/freq_asked
Previously in ASP.NET, I was able to achieve this by putting this in the routeConfig
:
routes.MapRoute(
name: "Contacts",
url: "contact_the_support_team",
defaults: new { controller = "Home", action = "Contacts" }
);
How do I achieve the same in ASP.NET Core?
I have not been able to create anything that works in the program.cs
file.
How do I change the URL for Razor pages from the default format like http://localhost:5088/Home/Faq, to a specific URL such as http://localhost:5088/freq_asked
Based on your shared code snippet and description, in order to change the URL for Razor pages in an ASP.NET Core MVC project from the default format we should use Conventional routing
As you may know in asp.net core regardless of its version it has ControllerEndpointRouteBuilderExtensions that includes the method MapControllerRoute
we can use that what you are trying to achieve.
First of all, you should use MapControllerRoute to define custom routes in your Program.cs file. Must remember that custom routes should be defined before the default route to take precedence.
In addition to that, make sure that your controller and action method names are consistent with the routes you are defining.
Let's have a look in practice how we can implement that:
Program.cs file:
app.MapControllerRoute(
name: "customFaq",
pattern: "freq_asked",
defaults: new { controller = "Home", action = "Faq" }
);
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Controller:
Your controller should hava action like below:
public IActionResult Faq()
{
return View();
}
So when you would hit https://localhost:7246/freq_asked
soon it would read the defination from route pattern
and reroute to your expected route.
Output:
Note: Keep in mind whatever you would be written here in pattern: "freq_asked"
that would be your URL path. Please refer to this official document if you want to study more.