我的asp.net mvc app中有两条路线
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default no language",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
当我在浏览器中输入网址http://localhost/gallery
时,我已重定向到http://localhost/
,当我尝试http://localhost/gallery/index
时,我发现了404错误
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /gallery/index
当我将任何实现的语言添加到url(http://localhost/en/gallery
)时,应用程序正在运行。
我是路由和网络应用程序编程的新手,所以如果有人可以通过详细解释如何解决这个问题我会帮助我。
答案 0 :(得分:1)
问题是你有两条路线,但是第一条路线总是会绑定,因为它在绑定{culture}/{controller}/{action}/{id}
时无法区分{controller}/{action}/{id}
和/gallery
之间的区别 - 是不是文化或只是一个控制器名称?
没有检查就无法判断,它只会绑定第一场比赛。
如果删除默认值,那么它可能会起作用,但您始终必须指定操作和控制器:
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetDefaultCulture(),
/* controller = "Home", action = "Index",*/ id = UrlParameter.Optional }
);
{culture}/{controller}/{action}/{id}
现在将绑定:
和{controller}/{action}/{id}
将绑定:
您的另一个选择是创建custom route constraint以验证第一个值是否为有效的文化值:
public class IsValidCultureConstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
if (string.IsNullOrWhiteSpace(values["culture"]))
{
return this.IsValidCulture();
}
return false;
}
private bool IsValidCulture(string cultureString)
{
//
// Logic here to check valid culture(s)
//
// Example
if (String.Equals(cultureString.Trim(), "en",
StringComparison.OrdinalIgnoreCase))
{
// English is valid
return true;
}
return false;
}
}
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetDefaultCulture(),
id = UrlParameter.Optional,
constraints: new { culture = new IsValidCultureConstraint() }
});
有了这个,如果输入到URL中的值是有效的文化,它将只匹配第一个路径。当然,您需要提供正确执行检查的逻辑。