MVC C# 自定义 MvcRouteHandler - 如何?
有人有提供自定义 MvcRouteHandler 的经验吗? 在我的应用程序中,我想实现一个全球化模式,例如 http://mydomain/en/about 或 http://mydomain/de/about。
至于持久性,我希望在请求到达时立即读取 cookie,并且如果此 cookie 中有语言设置,则应用它(因此用户到达 http://mydomain/例如,将被转移到http://mydomain/en/)。 如果没有 cookie,我想获取浏览器支持的第一种语言,应用该语言并将其存储在该 cookie 中。
我想这不能通过 mvc 在其初始项目模板中提供的标准路由机制来完成。 在新闻组中,我得到了查看 MvcRouteHandler 并实现我自己的提示。 但很难找到如何做到这一点的示例。
有任何想法吗?
Does anyone have experiences in providing a custom MvcRouteHandler? In my application I'd like to implement a globalization-pattern like http://mydomain/en/about or http://mydomain/de/about.
As for persistance, I'd like to have a cookie read as soon as a request arrives and if there is a language setting in this cookie apply it (so a user arriving at http://mydomain/ would be transferred to http://mydomain/en/ for example). If there is no cookie present, I'd like to get the first language the browser supports, apply this one and store it in this cookie.
I guess this can't be done with the standard routing mechanism mvc provides in it's initial project template. In a newsgroup I got the tip to have a look at the MvcRouteHandler and implement my own. But its hard to find a sample on how to do that.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用 ASP.NET MVC 的默认模板来完成此操作,我正在做类似的事情。 只需将路由构建为 {language}/{controller}/{action}/{id}
只需设置一条默认路由,该路由会转到检查语言 cookie 的控制器,并根据该 cookie 重定向用户。
You should be able to do this with ASP.NET MVC's default template, I'm doing something similar. Just build your routes as {language}/{controller}/{action}/{id}
Just set a default route that goes to a controller that checks for the language cookie, and redirects the user based on that cookie.
我不认为您所做的事情需要自定义路由处理程序。
对于“全球化”URI,常规 MVC 路由(具有“locale”参数必须等于“en”、“de”等约束)就可以了。 该约束将阻止非全球化 URI 匹配该路由。
对于“非全球化”URI,创建一个“包罗万象”的路由,仅重定向到默认或设置 cookie 的区域设置 URI。
将“全球化”路由放在 Global.asax 中的“catch-all”路由上方,以便“已全球化”URI 不会发生重定向。
如果您希望某个 URI 模式触发非控制器上的操作,则需要创建一个新的路由处理程序。 但我不认为这就是你在这里要处理的问题。
I don't believe a custom route handler is required for what you are doing.
For your "globalized" URIs, a regular MVC route, with a constraint that the "locale" parameter must be equal to "en", "de", etc., will do. The constraint will prevent non-globalized URIs from matching the route.
For a "non-globalized" URI, make a "catch-all" route which simply redirects to the default or cookie-set locale URI.
Place the "globalized" route above the "catch-all" route in Global.asax, so that "already-globalized" URIs don't fall through to the redirection.
You would need to make a new route handler if you want a certain URI pattern to trigger something that is not an action on a controller. But I don't think that's what you're dealing with, here.