- 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();
}
}
- 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();
}
}
- 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);
}
}
- 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>
- 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...
}
- 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();
}
}