英文:
how get query string with route attribute
问题
我的项目是.NET Core,如果我打开这个URL domain.com?param1=val1&param2=val2
,它会命中这个操作:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
而我想要的是,如果有人请求像这样的URL domain.com?param1=val1&param2=val2
,就命中这个控制器 RouteController => Index()
:
public class RouteController : Controller
{
[Route(@"{*:regex(([^=]+)\=([^&]+))")]
public IActionResult Index()
{
return View();
}
}
我认为我应该使用 [Route(@"{*:regex(([^=]+)\=([^&]+))")]
,但它不起作用!
英文:
My project is .net core and if I open this URL domain.com?param1=val1&param2=val2
it hit this action:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
in stand of HomeController ==> Index()
I want if someone requests URL like this domain.com?param1=val1&param2=val2
hit this controller RouteController ==> Index()
:
public class RouteController : Controller
{
[Route(@"{*:regex(([^=]+)\=([^&]+))")]
public IActionResult Index()
{
return View();
}
}
I think I should use [Route(@"{*:regex(([^=]+)\=([^&]+))")]
but it doesn't work!
答案1
得分: 3
你想要实现的场景是,当用户发送带有 domain.com
的请求时,它将正常路由到 Home/Index
,但当用户发送带有 domain.com?{任意查询字符串}
的请求时,它将路由到 Route/Index
?
我尝试自定义了 IRouteConstraint
并将其添加到路由模板中,希望这是您想要的:
public class MyRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext.Request.Query.Count > 0)
{
// 如果存在查询字符串,则路由到 Route/Index
return false;
}
// 如果没有查询字符串,则路由到 Home/Index
return true;
}
}
Program.cs
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}",
constraints: new { customConstraint = new MyRouteConstraint() }
);
app.MapControllerRoute(
name: "query",
pattern: "{controller=route}/{action=Index}"
);
演示动画
英文:
Do you wanna achieve the scenario like when user send request with domain.com
, It will route to Home/Index
normally, But when user send request with domain.com?{any query string}
, It will route to Route/Index
?
I try to custom IRouteConstraint
and add it will the route templated, Hope it is what you want.
public class MyRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext.Request.Query.Count > 0)
{
// Route to Route/Index if query string is present
return false;
}
// Route to Home/Index if no query string is present
return true;
}
}
Program.cs
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}",
constraints: new { customConstraint = new MyRouteConstraint() }
);
app.MapControllerRoute(
name: "query",
pattern: "{controller=route}/{action=Index}"
);
Gif Demo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论