And*_*phy 5 c# asp.net-mvc asp.net-mvc-4 attributerouting
我需要一种方法来根据我的MVC应用程序中的用户属性,在生成URL时以编程方式选择选择哪个RoutePrefix
我有一个MVC 4应用程序(使用AttributeRouting NuGet包)
由于托管环境的要求,我必须为我的许多操作设置两条路由,以便托管环境可以具有不同的访问权限.
我通过装饰我的控制器来解决这个问题[RoutePrefix("full")] [RoutePrefix("lite)].允许通过/ full/{action}和/ lite/{action}访问每个操作方法.
这非常有效.
[RoutePrefix("full")]
[RoutePrefix("lite")]
public class ResultsController : BaseController
{
// Can be accessed via /full/results/your-results and /lite/results/your-results and
[Route("results/your-results")]
public async Task<ActionResult> All()
{
}
}
Run Code Online (Sandbox Code Playgroud)
但是,每个用户只应在其URL中使用full或lite,这取决于该用户的某些属性.
显然,当我使用RedirectToAction()或@Html.ActionLink()它只会选择第一个可用的路线,并不会保留"正确"的前缀.
我想我可以覆盖该RedirectToAction()方法以及添加我自己的@Html.ActionLink()方法版本.
这将有效,但它将涉及一些讨厌的代码,我生成URL,因为我得到的是一个表示动作和控制器的字符串,但不是反映的类型.也可能有路由属性,例如在我的示例中,所以我将不得不复制许多内置代码的MVC.
对于我想解决的问题,有没有更好的解决方案?
怎么样的:
[RoutePrefix("{version:regex(^full|lite$)}")]
Run Code Online (Sandbox Code Playgroud)
然后,当您创建链接时:
@Url.RouteUrl("SomeRoute", new { version = "full" })
Run Code Online (Sandbox Code Playgroud)
要么
@Url.RouteUrl("SomeRoute", new { version = "lite" })
Run Code Online (Sandbox Code Playgroud)
您甚至可以执行以下操作来保留已设置的内容:
@Url.RouteUrl("SomeRoute", new { version = Request["version"] })
Run Code Online (Sandbox Code Playgroud)
我最终找到了解决方案
我刚刚覆盖了默认路由以包含此内容。ASP.Net 自动保留用户类型值,并在重新生成路由时将其放回原处
const string userTypeRegex = "^(full|lite)$";
routes.Add("Default", new Route("{usertype}/{controller}/{action}/{id}",
new { controller = "Sessions", action = "Login", id = UrlParameter.Optional }, new { usertype = userTypeRegex }));
Run Code Online (Sandbox Code Playgroud)
我发现这不适用于Route或RoutePrefix属性,因此我必须将它们全部删除。在这些情况下迫使我添加特定路线
routes.Add("Profile-Simple", new Route("{usertype}/profile/simple",
new { controller = "ProfileSimple", action = "Index" }, new { usertype = userTypeRegex }));
Run Code Online (Sandbox Code Playgroud)
我认为我的文件中的六条硬编码路由RouteConfig比必须手动向我生成 URL 的每个位置添加值(如 Chris 的解决方案)更好的解决方案。
| 归档时间: |
|
| 查看次数: |
11856 次 |
| 最近记录: |