How to Implement SEO friendly URL instead of default URL pattern in ASP.NET Core?

244 Views Asked by At

I have a comparison module and the screen is looks like this:

enter image description here

When the user types the name, autosuggest popup and comparison will be shown in a table.

Now when I look at the URL, it looks like this:

https://localhost:7043/Compare/ResultTwo?compareOne=4&compareTwo=2

ASP.NET Core automatically added that. But I want a friendly URL like

https://localhost:7043/Compare/nvidia-vs-raiden

Compare is my controller and ResultTwo is my action.

public IActionResult ResultTwo(string compareOne, string compareTwo)
{
    _model.Item1 = Convert.ToInt16(compareOne);
    _model.Item2 = Convert.ToInt16(compareTwo);

    return View(FullPathsOfViews.CompareSpecs, _model);
}

I believe sharing the whole code will not be necessary, as this is just the default behavior of ASP.NET Core. Nothing was changed inside the code. The rest of the code only has business logic. Program.cs also has not been changed.

If you want a specific code piece please mention, I love to share it.

How to achieve this?

1

There are 1 best solutions below

0
Xinran Shen On

You can create a route template to match this url, Here is a working demo

Program.cs

app.MapControllerRoute(                    
  name: "customCompareRoute",
  pattern: "Compare/{compareOne}-vs-{compareTwo}",
  defaults: new { controller = "Home", action = "ResultTwo" }
);

app.MapControllerRoute(
   name: "default",
   pattern: "{controller=Home}/{action=Index}/{id?}"
);

View

<form method="get" >
    <input type="text" id="compareOne" name="compareOne" />
    <input type="text" id="compareTwo" name="compareTwo" />
    <button type="button" id="btn" >Compare</button>
</form>

@section Scripts{
   <script>

        document.getElementById('btn').onclick = submit

            function submit() {
                let value1 = document.getElementById('compareOne').value
                let value2 = document.getElementById('compareTwo').value
            window.location.href = `https://localhost:7144/Compare/${value1}-vs-${value2}`
            }

    </script>
}

Demo

enter image description here