How to add ? to the URL routing

Venkat 1 Reputation point
2021-11-19T14:55:15.237+00:00

I have created an application using ASP.NET MVC core 5.0 where we have the routing in place.

One of the requirement is retain UTM tags in the URL as a query string along with the routing. But we are not able to achieve because its not accepting "?" in the URL showing some compile time error.

Kindly advise the same.

URL: https://abc.om/?utm_source=test&utm_data=nodata..,

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2021-11-19T15:46:53.98+00:00

    Only the url path is used for routing, the query string is used for named route parameters. User friendly urls are where the query string values are passed as a path rather than query string args. Routing handles this case by mapping the path args back to named route parameters.

    If you want query string args to be part of routing, you will need to write a custom routing component, or middleware that does url rewriting.


  2. Venkat 1 Reputation point
    2021-11-19T15:49:18.543+00:00

    Under home folder there is an index.html file where we are rendering static and dynamic content from DB.

    in the homecontroller.cs we have the below code

    [Route("")]
    [Route(utmquerystring)]
    public IActionResult Index([FromQuery]string utm)
    {
    // dynamic code to pull the data from DB and return to the view
    return View(viewModel);
    }

    In the startup.cs file we have the below code in Configure method.

    app.UseMvc(routes =>
    {
    routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
    });

    when we run the code the initial URL shows http://localhost:40404

    And then pass the additional parameter like http://localhost:40404/?utm=test but once the page loaded completed its stripping out the ?utm=test from the URL but we need to retain the query string even after load the page completely.

    Please let me know if you need any other details.