【问题标题】:Intercepting ASP.NET MVC routes拦截 ASP.NET MVC 路由
【发布时间】:2011-11-22 00:29:22
【问题描述】:

在服务器端创建链接时,我需要转换一些 url 参数。

例子:

@html.ActionLink("text","index","Home",null,new { id=Model.Id });

现在我必须转换 id 参数,以便我可以简单地将其转换并将其传递给对象 objectRoute 参数,或者我可以简单地覆盖 ActionLink。但问题是我必须对整个项目进行重构。

所以我正在寻找一种拦截机制或处理程序机制的方法。

有什么解决办法吗?

【问题讨论】:

  • 我无法完全理解您的问题,所以我会给您链接:ASP.NET MVC Routing Overview。希望对你有所帮助
  • @Pankaj Upadhyay - 认为 id 参数是 2,我想将 2 转换为“xxkylmn”。我可以在通过之前对其进行转换,但我不想对整个项目进行重构。现在你清楚了吗?
  • 在这种情况下,我认为您需要进行 URL 重写而不是自定义 ASP.NET 路由。
  • 或者在操作中重定向到正确的操作/URL。
  • 您能说明一下您要完成的工作吗?可能包括您尝试链接的控制器操作以及“转换”和“转换”的含义。

标签: c# .net asp.net-mvc routing


【解决方案1】:

您可以尝试使用 ActionFilterAttribute:

public class ConversionAttribute : ActionFilterAttribute
{    
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        var idValue = filterContext.RouteData.Values["id"];
        var convertedIdValue = ConvertId(idValue);

        var newRouteValues = new RouteValueDictionary(filterContext.RouteData.Values);
        newRouteValues["id"] = convertedIdValue;

        filterContext.Result = new RedirectToRouteResult(newRouteValues);
    }
}

然后您需要将该属性应用于您希望发生这种情况的操作:

[Conversion]
public ActionResult Index(int id) 
{
    // Your logic
    return View();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    相关资源
    最近更新 更多