使用路線約束求解,基於this answer
public class NotInRouteConstraint : IRouteConstraint
{
private readonly string _notInString;
public NotInRouteConstraint(string notInString)
{
_notInString = notInString;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (string.IsNullOrEmpty(_notInString))
return true;
var notList = _notInString.Split('|').Select(s => s.Trim().ToLower()).ToList();
var value = values[parameterName] as string;
if (!string.IsNullOrEmpty(value))
{
return !notList.Contains(value.ToLower());
}
return true;
}
}
用法代碼:
//this is in another area
context.MapRoute(
"Users_Bootstrap",
"{ulrPrefix}/{*catchall}",
new { controller = "Start", action = "Index" },
constraints: new { ulrPrefix = new NotInRouteConstraint(RouteConfig.ReservedUrlPrefix.JoinStrings("|")) }
);
希望有另一個更好的解決方案。謝謝。
編輯
更多更快一點:
public class NotInRouteConstraint : IRouteConstraint
{
private readonly IEnumerable<string> _notInString;
public NotInRouteConstraint(IEnumerable<string> notInString)
{
_notInString = notInString;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (_notInString == null)
return true;
var value = values[parameterName] as string;
if (!string.IsNullOrEmpty(value))
{
return !_notInString.Contains(value.ToLower());
}
return true;
}
}
和
context.MapRoute(
"Users_Bootstrap",
"{ulrPrefix}/{*catchall}",
new { controller = "Start", action = "Index" },
constraints: new { ulrPrefix = new NotInRouteConstraint(RouteConfig.ReservedUrlPrefix.Select(s=>s.Trim().ToLower())) }
);