各位大大好
想請問屬性route的設定
[Route("AAA")]
[Route("{subDoname1}/AAA")]
[Route("{subDoname1}/{subDoname2}/AAA")]
[Route("{subDoname1}/{subDoname2}/{subDoname3}/AAA")]
[Route("{subDoname1}/{subDoname2}/{subDoname3}/{subDoname4}/AAA")]
[Route("BBB")]
[Route("{subDoname1}/BBB")]
[Route("{subDoname1}/{subDoname2}/BBB")]
[Route("{subDoname1}/{subDoname2}/{subDoname3}/BBB")]
[Route("{subDoname1}/{subDoname2}/{subDoname3}/{subDoname4}/BBB")]
[Route("CCC")]
[Route("{subDoname1}/CCC")]
[Route("{subDoname1}/{subDoname2}/CCC")]
[Route("{subDoname1}/{subDoname2}/{subDoname3}/CCC")]
[Route("{subDoname1}/{subDoname2}/{subDoname3}/{subDoname4}/CCC")]
有更好的做法嗎QQ
因為系統預設可以讓客戶墊到四層,但這寫法看了實在感覺很糟
中間墊的內容,我們並不是很在意,我們只需要知道最後一個是什麼決定要不要進這個controller
爬文爬了很久,沒有找到那種不管中間有多少,僅符合最後一個的ˊˋ
硬寫看看,不知道合不合您的需求,可以根據需要改一下Regex:
public class CustomRouteConstraint : IRouteConstraint
{
private Regex _regex;
public CustomRouteConstraint()
{
_regex = new Regex(@"^([\w\/]*\/)?(?<c>.*?)$", RegexOptions.CultureInvariant);
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (!values.TryGetValue("controller", out object controllerNameObj) || controllerNameObj == null)
return false;
var controllerName = controllerNameObj.ToString();
if (!values.TryGetValue(routeKey, out object routeStringObj) || routeStringObj == null)
return false;
var routeString = routeStringObj.ToString();
if (!_regex.IsMatch(routeString))
return false;
var match = _regex.Match(routeString);
var c = match.Groups["c"].ToString();
return controllerName.Equals(c, StringComparison.InvariantCultureIgnoreCase);
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting(options =>
{
options.ConstraintMap.Add("customRoute", typeof(CustomRouteConstraint));
});
}
[Route("{**path:customRoute}")]
public class TestController : Controller
{
public IActionResult Index()
{
return Ok();
}
}