Asp.Net Core Routing using a parameter transformer and depending on the culture

Viewed 656

I want to customize routes depending on the culture of web application to have a 'friendly' url (to optimize SEO). For example, for the controller called "FirstItemController", and view called "TheIndexView":

  • www.myapp.com/fr/mon-premier-element/la-vue-index
  • www.myapp.com/en/my-first-item/the-index-view
  • www.myapp.com/es/mi-primer-elemento/la-vista-index

Asp.Net Core 2.2 introduces the concept of Parameter Transformers to routing (https://blogs.msdn.microsoft.com/webdev/2018/10/17/asp-net-core-2-2-0-preview3-now-available/ + https://www.hanselman.com/blog/ASPNETCore22ParameterTransformersForCleanURLGenerationAndSlugsInRazorPagesOrMVC.aspx)

I know, theses articles was wrote for 2.2.0 preview 3.

For the moment, I've create the SlugifyParameterTransformer class and register it in AddMvc options :

public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
    public string TransformOutbound(object value)
    {
        if (value == null) { return null; }

        // Slugify value
        return Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
    }
}

I've tried two approaches in routes options:

app.UseMvc(routes => routes.MapRoute("default", "{culture=fr}/{controller=Home}/{action=Index}/{id?}")); 
// works

// AND

app.UseMvc(routes => routes.MapRoute("default", "{culture=fr}/{controller=Home:slugify}/{action=Index:slugify}/{id?}"));
// dosn't works, I don't know where I declare "slugify" for the url template

It work's: MyFirstItemController.TheIndexView url is "my-first-item/the-index-view". Now, how can I localize my urls?

I've tried to add the RouteAttribute and HttpGetAttribute:

[Route("{culture=fr}/mon-premier-element")]
[Route("{culture=en}/my-first-item")]
public class MyFirstItemController : Controller
{
    [HttpGet("???????")] // for moment: [controller]/[action]
    public IActionResult TheIndexView()
    { /*...*/ }
}

I don't know what can I use in Name value of HttpGetAttribute. These urls works:

  • fr/mon-premier-element/ (good)
  • en/mon-premier-element/ (NOT good)
  • fr/my-first-item (NOT good)
  • en/my-first-item (good)
0 Answers
Related