【问题标题】:How to access UrlHelper.Action or similar from within Global asax如何从 Global asax 中访问 UrlHelper.Action 或类似内容
【发布时间】:2015-08-27 00:05:06
【问题描述】:

我正在尝试为“已收到”的错字准备 301 重定向

我正在努力寻找从动作和控制器名称中获取 url 的方法。

我知道 UrlHelper.Action,但它在 Global.asax 中不存在。我如何获得此方法的访问权限?:

// Add permanent redirection for retired pages (Application_BeginRequest())
if (HttpContext.Current.Request.Url.LocalPath.ToLower().StartsWith("/blah/listrecieved"))    
{
    HttpContext.Current.Response.RedirectPermanent(/*Need url generated from action and controller*/);
}

或者我已经创建了一个路由,如果我应该这样获取字符串,这也很好,但我不确定如何:

routes.MapRoute(
    name: "blah-list-received",
    url: "blah/list-received",
    defaults: new { controller = "Blah", action = "ListReceived" }
);

例如,它可能看起来像这样:

// Add permanent redirection for retired pages
if (HttpContext.Current.Request.Url.LocalPath.ToLower().StartsWith("/blah/listrecieved"))    
{
    HttpContext.Current.Response.RedirectPermanent(routes.GetUrl( "blah-list-received" ) );
}

【问题讨论】:

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


    【解决方案1】:

    你需要自己构造UrlHelper

    var url = new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes)
                 .Action("YourAction",
                         "YourController",
                         new { paramName = paramValue });
    

    MSDN

    【讨论】:

    • 我认为您提供的第一行有一些错字。感谢您的链接!
    • 同样的问题,你的括号太多了 :D 谢谢你,非常感谢你的帮助......现在检查它是否有效!
    • 这里说明路由数据参数不能为空:Value cannot be null. Parameter name: routeData
    • 谢谢伙计,现在我必须整理一下这里不可用的上下文。关于 301 应该如何实际工作的任何想法?
    • ahahah 显然是错误的,我在 application_start 中,现在移至 Application_BeginRequest() .. 它有效。谢谢大哥!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    相关资源
    最近更新 更多