Reputation: 51
i am trying to implement a route with an optional value (language) and if it is not given by url, a default value for it, for example "de".
i have following test-controllers:
public IActionResult Index(string lang = "de")
{
return View();
}
public IActionResult Privacy(string lang = "de")
{
return View();
}
and following router configuration:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{lang?}/{action=Index}/{id?}");
});
so my expected result should be:
path: expected invocation: actual invocation
localhost:44305/ --> invoke Index(string lang = "de") --> working
locahlhost:44305/home/en/index --> invoke Index(string lang = "en") --> working
localhost:44305/home/privacy --> invoke Privcay(string lang = "de") --> ERROR!!! invoking Index(string lang = "privacy")
localhost:44305/home/de/privacy --> invoke Privacy(string lang = "de") --> working
localhost:44305/home/en/privacy --> invoke Privacy(string lang = "en") --> working
As you can see, i got the problem with the url ../home/privacy, cause the controller thinks, its my new language string.
Are there any suggestions how i can prevent it?
Upvotes: 0
Views: 369
Reputation: 36645
Change your route template like below:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "lang",
pattern: "{controller=Home}/{lang?}/{action=Index}/{id?}");
});
Upvotes: 1