Asp.net mvc 如何从mvc4中的控制器操作方法向请求的URL追加字符串

Asp.net mvc 如何从mvc4中的控制器操作方法向请求的URL追加字符串,asp.net-mvc,asp.net-mvc-4,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc 4,Asp.net Mvc Routing,我正在开发一个网站,其中包含一些使用MVC4和实体框架的教程。 所有教程都将保存在数据库中,并基于请求URL中提供的教程Id(比如TId),它将在操作方法中检索有关该教程的所有信息,并在视图中呈现并显示给用户。下面提到了一个示例URL URL:www.mysite.com/Tutorials/Show/452 其中,Tutorials是控制器名称,Show是动作方法名称 这里是工业贸易署。因此,当请求此URL时,将显示TId 452教程。但我想要的是,我想在末尾附加虚线教程名称,如下所示 www

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

URL:www.mysite.com/Tutorials/Show/452

其中,Tutorials是控制器名称,Show是动作方法名称

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

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

我可以用“-”替换空格并生成字符串,但我无法找到将其附加到URL的方法

这与stackoverflow站点完美配合。 例如,即使我们请求,Id为“20035665”的问题仍会显示,URL将更改为


有人能帮我吗?

你可以有一个如下的路由配置,当你创建URL时,你可以将教程标题传递给一个转换给定URL的方法

示例

路由内配置

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>

您可以使用如下所示的路由配置,当您创建URL时,可以将教程标题传递给转换给定URL的方法

示例

路由内配置

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>

假设我正确理解了您的问题,下面是我建议的解决方案:

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

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 }
        );
    }
}
然后在教程控制器中:

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
公共行动结果索引()
{
//在这里,您可以显示最新教程或其他内容的列表
返回视图();
}
//获取:/Tutorials/1(将重定向到下面的一个)
//获取:/Tutorials/1/Intro-into-ASP\u NET-MVC
公共操作结果显示(int-id,字符串标题)
{
string key=string.Format(“tutorial-{0}”,id.ToString());
Tutorial model=TempData[key]作为教程;
//如果这不是重定向
if(model==null)
{
模型=getutorial(id);
}
//清除标题参数
字符串urlParam=model.Title.Replace(“”,“-”);
//显然,如果您的url包含“”,IIS假定您正在请求资源
urlParam=urlParam.Replace('.','');

//编码特殊字符,如“\”、“/”、“>”、“假设我正确理解了您的问题,下面是我建议的解决方案:

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

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 }
        );
    }
}
然后在教程控制器中:

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
公共行动结果索引()
{
//在这里,您可以显示最新教程或其他内容的列表
返回视图();
}
//获取:/Tutorials/1(将重定向到下面的一个)
//获取:/Tutorials/1/Intro-into-ASP\u NET-MVC
公共操作结果显示(int-id,字符串标题)
{
string key=string.Format(“tutorial-{0}”,id.ToString());
Tutorial model=TempData[key]作为教程;
//如果这不是重定向
if(model==null)
{
模型=getutorial(id);
}
//清除标题参数
字符串urlParam=model.Title.Replace(“”,“-”);
//显然,如果您的url包含“”,IIS假定您正在请求资源
urlParam=urlParam.Replace('.','');

//编码特殊字符,如“\”、“/”、“>”、“
Tutorials
是控制器的名称,对吗?我可以问一下为什么要在URL中附加名称,这会使URL变长吗?使用Tid,服务器无论如何都会知道教程名称。第二,即使您有充分的理由传递教程名称,也有其他方法将数据发送到服务器。@Stefan Baiu。。是的。Tutorials是控制器名称,Show是操作方法名称。@SBirthare..我没有在url中包含标题以将输入数据传递给服务器,而是为了使url看起来友好。只要看一下url,我们就应该能够知道标题。@kewlcoder:这也改进了SEO,我正在使用我在我的回答中提到的方法站点。
Tutorials
是控制器的名称,对吗?我可以问一下为什么要在URL中附加名称,这会使URL变长吗?使用Tid,服务器无论如何都会知道教程名称。第二,即使您有充分的理由传递教程名称,也有其他方法将数据发送到服务器。@Stefan Baiu..是的。Tutorials是控制器名称和操作方法名称如何。@SBirthare..我没有在url中包含标题以将输入数据传递给服务器,而是为了使url看起来友好。只要看一下url,我们就应该能够知道标题。@kewlcoder:这也改进了SEO,我在我的站点中使用了我在回答中提到的方法。到github的链接是断开的链接到github的连接已断开