MVC 路由 - 通配符 URL,但受限
MVC Routing - wildcard URL, but constrained
我基本上想这样做:
routes.MapRoute(
"Pass-through",
"/api/{*url}",
new { controller = "PassThrough", action = "PassThroughToApi" });
我将请求定向到的控制器具有:
public ContentResult PassThroughToApi(string url = null)
但是,我希望能够同时约束URL。如:
routes.MapRoute(
"Pass-through",
"/api/v1/some/specific/address/{whatever}/{parameters}",
new { controller = "PassThrough", action = "PassThroughToApi" });
但我仍然希望控制器将请求的 URL 作为变量获取,我不关心获取实际参数,只要 URL 与模式匹配即可。或者我应该只是从另一个地方获取请求的 URL,比如上下文,而不是作为参数传递给它?
public class ApiRedirectingConstraint : IRouteConstraint
{
private string _matchUrl;
public ApiRedirectingConstraint(string matchUrl)
{
_matchUrl = matchUrl;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string url = (string)values["url"];
bool isMatch = true;
//check url for specific match with _matchUrl
return isMatch;
}
}
并将其分配给 Pass-through
路线
routes.MapRoute(
"Pass-through",
"/api/{*url}",
new { controller = "PassThrough", action = "PassThroughToApi" },
new { apiRedirect = new ApiRedirectingConstraint("/api/v1/some/specific/address/{whatever}/{parameters}") }
);
我基本上想这样做:
routes.MapRoute(
"Pass-through",
"/api/{*url}",
new { controller = "PassThrough", action = "PassThroughToApi" });
我将请求定向到的控制器具有:
public ContentResult PassThroughToApi(string url = null)
但是,我希望能够同时约束URL。如:
routes.MapRoute(
"Pass-through",
"/api/v1/some/specific/address/{whatever}/{parameters}",
new { controller = "PassThrough", action = "PassThroughToApi" });
但我仍然希望控制器将请求的 URL 作为变量获取,我不关心获取实际参数,只要 URL 与模式匹配即可。或者我应该只是从另一个地方获取请求的 URL,比如上下文,而不是作为参数传递给它?
public class ApiRedirectingConstraint : IRouteConstraint
{
private string _matchUrl;
public ApiRedirectingConstraint(string matchUrl)
{
_matchUrl = matchUrl;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string url = (string)values["url"];
bool isMatch = true;
//check url for specific match with _matchUrl
return isMatch;
}
}
并将其分配给 Pass-through
路线
routes.MapRoute(
"Pass-through",
"/api/{*url}",
new { controller = "PassThrough", action = "PassThroughToApi" },
new { apiRedirect = new ApiRedirectingConstraint("/api/v1/some/specific/address/{whatever}/{parameters}") }
);