【问题标题】:There is a way to rename the controller on OnActionExecuting ASP MVC 4?有一种方法可以重命名 OnActionExecuting ASP MVC 4 上的控制器吗?
【发布时间】:2015-01-30 07:51:30
【问题描述】:

我尝试根据当前语言创建一个 url 重写器。例如,如果我有控制器文章,对于每种语言,我都有如下记录:

public class ControllerRewriter
{
    public LanguageName { get; set; }
    public NiceName { get; set; }
    public Controller { get; set; }
}

还有我搜索的 ControllerRewriter 列表。

public class ControllerRewriterList: List<ControllerRewriter>
{
    public string GetController(string niceName)
    {
        var cr = this.FirstOrDefault( c => c.NiceName == niceName);
        if( cr == null )
            return niceName;
        else
            return cr.Controller; 
    }
}

在一个Controller基类中,我重写了OnActionExecuting方法,以拦截控制器的niceName,然后用控制器的真实名称重写它,但是我失败了......

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _actionName = filterContext.ActionDescriptor.ActionName.ToLower();
        //here I get a nice name of controller according with the current language
        _controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();

        //rewrite the controller with the real name of controller
        //this line doesn't work AND I NEED A SOLUTION ( thanks! )
        filterContext.ActionDescriptor.ControllerDescriptor.ControllerName = crList.GetController(_controllerName);

        base.OnActionExecuting(filterContext);
    }

您对我如何重写控制器名称有任何想法/建议,在 OnActionExecuting 或其他方法中......?

更新:RedirectToRouteResult 不是一个选项,因为它会改变当前的 url。 :-)

谢谢, 奥维迪乌

【问题讨论】:

  • 我认为您在 OnActionExecuting 方面走在了正确的轨道上。我记得很久以前用那种方法(我记得)做动作和控制器的切换。我看看能不能找到代码。

标签: c# asp.net asp.net-mvc url-rewriting


【解决方案1】:

你可以做类似的事情

filterContext.Result = new RedirectToRouteResult(routeName, routeValues);

【讨论】:

  • 是的,我知道那个解决方案,但这会重定向我……它会用“丑陋的”改变当前(漂亮的)url,我不想要这个。
猜你喜欢
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多