我的RouteConfig中有这个
:routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "StoreSearch",
url: "{storeName}",
defaults: new { controller = "Search", action = "Store" }
);
基本上我有一条第二条路线,所以如果我输入localhost:9000/facebook
时没有这样的控制器,其名称为facebook
,那么我的第二条路由器应该选择facebook
作为{{1} },然后点击我的storeName
控制器的Search
操作。但目前我得到404。
有什么主意该如何解决?
答案 0 :(得分:1)
如果您有一组特定的商店或验证它们的方法,则可以向路线添加约束。
要添加具有匹配谓词的通用约束
public class ServerRouteConstraint : IRouteConstraint
{
private readonly Func<Uri, bool> _predicate;
public ServerRouteConstraint(Func<Uri, bool> predicate)
{
this._predicate = predicate;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return this._predicate(httpContext.Request.Url);
}
}
然后在路由中添加一个参数
routes.MapRoute(
name: "StoreSearch",
url: "{storeName}",
defaults: new { controller = "Search", action = "Store" }, constraints:
//this could be new { controller ="pattern" }
new {
serverRoute = new ServerRouteConstraint(url =>
{
//this will check that the route starts with a specific string in this case Settings
return url.PathAndQuery.StartsWith("/Settings",
StringComparison.InvariantCultureIgnoreCase);
})
});
有关示例,请检查:https://www.c-sharpcorner.com/UploadFile/dacca2/route-constraints-in-mvc/
此外,应从最具体的到最一般的添加路线。
答案 1 :(得分:0)
您应将任何自定义路线放置在Match
路线上方。
只需交换订单,您就可以开始
Default