【问题标题】:How to append string to the requested URL from controller action method in mvc4如何从 mvc4 中的控制器操作方法将字符串附加到请求的 URL
【发布时间】:2014-10-01 13:46:24
【问题描述】:

我正在开发一个网站,其中包含一些使用 MVC4 和实体框架的教程。 所有教程都将保存在数据库中,并根据请求的 URL 中提供的教程 ID(例如 TId),它将在操作方法中检索有关该教程的所有信息,并在视图中呈现并显示给用户。下面提到了一个示例 URL。

网址:www.mysite.com/Tutorials/Show/452

Tutorials 是控制器名称,Show 是操作方法名称。

这里的 452 是 TId。因此,当请求此 URL 时,将显示 TId 为 452 的教程。但我想要的是,我想在末尾附加虚线教程名称,如下所示。

www.mysite.com/Tutorials/Show/452/My-Test-Tutorial

我可以用“-”替换空格并生成字符串,但我想办法将它附加到 URL。

这与 stackoverflow 网站完美配合。 例如,即使我们请求 "In MVC4, how to redirect to a view from a controller action with parameters in the Url?",ID 为 "20035665" 的问题也会显示,并且 URL 将更改为 "In MVC4, how to redirect to a view from a controller action with parameters in the Url?"

谁能帮我解决这个问题?

【问题讨论】:

  • Tutorials 是控制器的名字吧?
  • 我能问一下为什么要在 URL 中附加名称,这会使 url 冗长吗?使用 Tid,服务器无论如何都会知道教程名称。其次,即使您有充分的理由传递教程名称,也可以通过其他方式将数据发送到服务器。
  • @Stefan Baiu .. 是的。 Tutorials 是控制器名称,Show 是动作方法名称。
  • @SBirthare.. 我不包括在 url 中用于将输入数据传递给服务器的标题,而是为了使 url 看起来友好。只要看一下 URL,我们应该就能知道标题。
  • @kewlcoder:这也改善了 SEO,我正在使用我在网站上的回答中提到的方法。

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing


【解决方案1】:

假设我正确理解了您的问题,以下是我提出的解决方案:

将以下更改添加到您的路由机制:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Tutorials",
            url: "Tutorials/{id}/{title}",
            defaults: new { controller = "Tutorials", action = "Show", title = UrlParameter.Optional },
            constraints: new { id = @"\d+" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

然后在您的 Tutorials 控制器中:

public class TutorialsController : Controller
{
    // GET: /Tutorials

    public ActionResult Index()
    {
        // here you can display a list of the most recent tutorials or whatever
        return View();
    }

    // GET: /Tutorials/1 (will be redirected to the one below)
    // GET: /Tutorials/1/Intro-into-ASP_NET-MVC

    public ActionResult Show(int id, string title)
    {
        string key = string.Format("tutorial-{0}", id.ToString());
        Tutorial model = TempData[key] as Tutorial;

        // if this is not a redirect
        if ( model == null )
        {
            model = GetTutorial(id);
        }

        // sanitize title parameter
        string urlParam = model.Title.Replace(' ', '-');
        // apparently IIS assumes that you are requesting a resource if your url contains '.'
        urlParam = urlParam.Replace('.', '_');
        // encode special characters like '\', '/', '>', '<', '&', etc.
        urlParam = Url.Encode(urlParam);

        // this handles the case when title is null or simply wrong
        if ( !urlParam.Equals(title) )
        {
            TempData[key] = model;
            return RedirectToAction("Show", new { id = id, title = urlParam });
        }

        return View(model);
    }

    private Tutorial GetTutorial(int id)
    {
        // grab actual data from your database
        Tutorial tutorial = new Tutorial { Id = 1, Title = "Intro into ASP.NET MVC" };
        return tutorial;
    }
}

更新:

上述解决方案将重定向
/Tutorials/1

/Tutorials/1/Intro-into-ASP_NET-MVC

如果您真的想在 url 中显示操作名称,例如 /Tutorials/Show/1/Intro-into-ASP_NET-MVC,您只需更改“教程”中的“url”即可" 路由到url: "Tutorials/Show/{id}/{title}"

您还可以将 RedirectToAction 替换为 RedirectToRoute("Default", new { id = id, title = urlParam });,这将确保它与名为“Default”的路由匹配,但这种方法会产生以下 url:www.mysite.com/Tutorials/Show/1? title=Intro-into-ASP_NET-MVC

【讨论】:

    【解决方案2】:

    您可以有如下的路由配置,当您创建 URL 时,您可以将教程标题传递给转换给定 text to URL friendly text 的方法。

    示例

    在路由配置中

    routes.MapRoute(
        name: "Tutorials",
        url: "{controller}/{action}/{tid}/{title}",
        defaults: new { controller = "Tutorials", action = "Show", tid = UrlParameter.Optional, title = UrlParameter.Optional }
    );
    

    创建 URL 时在视图中

    <a href='@Url.Action("Tutorials", "Show", new { tid = tutorial.ID, title = ToFriendlyUrl(tutorial.Title) })'>My Tutorial</a>
    

    然后在 Show 方法中

    public ActionResult Show(int tid, string title)
    {
        // if the title is missing you can do a redirect inside action method
    
        return View();
    }
    

    【讨论】:

    • github链接失效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2015-03-10
    相关资源
    最近更新 更多