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,815 questions
{count} votes

5 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 74,936 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.


  3. Austra, Barry 0 Reputation points
    2025-02-05T14:46:31.75+00:00

    you caqn read the querystring in the controller as well without needing to add the "Route" directive on the landing page view:
    HttpContext.Request?.Query.TryGetValue("querystring variable", out oQS);

    if (oQS.Count > 0)

    {

    sToken = oQS.FirstOrDefault();
    

    }

    0 comments No comments

  4. MohaNed Ghawar 155 Reputation points
    2025-02-05T18:10:45.2133333+00:00
    1. If you're using attribute routing, you can keep the query string parameters separate from the route:

    // Controller

    [Route("[controller]")]

    public class HomeController : Controller

    {

    // This will match: /Home/Index?utm_source=facebook&utm_medium=social
    
    [Route("Index")]
    
    public IActionResult Index([FromQuery] string utm_source, [FromQuery] string utm_medium)
    
    {
    
        // Access UTM parameters here
    
        return View();
    
    }
    

    }

    1. If you're using conventional routing in Startup.cs, keep it as is and accept query parameters in your action: // Startup.cs app.UseEndpoints(endpoints => {
      endpoints.MapControllerRoute(
      
          name: "default",
      
          pattern: "{controller=Home}/{action=Index}/{id?}");
      
      }); // Controller public class HomeController : Controller {
      public IActionResult Index(string utm_source, string utm_medium)
      
      {
      
          // Parameters will automatically bind from query string
      
          return View();
      
      }
      
      }
    2. To handle all UTM parameters in a clean way, create a model:

    public class UtmParameters

    {

    public string UtmSource { get; set; }
    
    public string UtmMedium { get; set; }
    
    public string UtmCampaign { get; set; }
    
    public string UtmTerm { get; set; }
    
    public string UtmContent { get; set; }
    

    }

    // Controller

    public class HomeController : Controller

    {

    public IActionResult Index([FromQuery] UtmParameters utm)
    
    {
    
        // Access utm.UtmSource, utm.UtmMedium etc.
    
        return View(utm);
    
    }
    

    }

    1. To generate URLs with UTM parameters in your views:

    // In your Razor view

    @Url.Action("Index", "Home", new {

    utm_source = "facebook", 
    
    utm_medium = "social" 
    

    })

    // Or using tag helpers

    <a asp-controller="Home"

    asp-action="Index"

    asp-route-utm_source="facebook"

    asp-route-utm_medium="social">Link Text</a>

    1. If you need to handle UTM parameters globally, create a middleware:

    public class UtmTrackingMiddleware

    {

    private readonly RequestDelegate _next;
    
    public UtmTrackingMiddleware(RequestDelegate next)
    
    {
    
        _next = next;
    
    }
    
    public async Task InvokeAsync(HttpContext context)
    
    {
    
        var utmParams = new Dictionary<string, string>();
    
        var query = context.Request.Query;
    
        // Collect all UTM parameters
    
        foreach (var param in query)
    
        {
    
            if (param.Key.StartsWith("utm_", StringComparison.OrdinalIgnoreCase))
    
            {
    
                utmParams[param.Key] = param.Value;
    
            }
    
        }
    
        // Store in TempData or Session if needed
    
        if (utmParams.Any())
    
        {
    
            context.Items["UtmParameters"] = utmParams;
    
        }
    
        await _next(context);
    
    }
    

    }

    // Register in Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {

    // Other middleware...
    
    app.UseMiddleware<UtmTrackingMiddleware>();
    
    // Other middleware...
    

    }

    1. To preserve UTM parameters across redirects:

    public class HomeController : Controller

    {

    public IActionResult Index()
    
    {
    
        var currentUrl = Request.QueryString.Value; // Gets all query parameters
    
        return RedirectToAction("OtherAction", new { returnUrl = currentUrl });
    
    }
    
    public IActionResult OtherAction(string returnUrl)
    
    {
    
        // Use returnUrl to maintain UTM parameters
    
        return View();
    
    }
    

    }

    0 comments No comments

  5. daniel jarquin 0 Reputation points
    2025-02-05T21:29:42.5666667+00:00

    If you're building a website for Lost Life APK and want to include query parameters (? in URLs) for dynamic routing or user-specific content, here's a breakdown for common web frameworks along with unique content ideas to boost engagement.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.