C# 使用MVC直接路由到自定义搜索

C# 使用MVC直接路由到自定义搜索,c#,asp.net-mvc,asp.net-mvc-4,routes,C#,Asp.net Mvc,Asp.net Mvc 4,Routes,我需要使用MVC创建自定义路线以构建自定义搜索: 默认主索引的操作: public virtual ActionResult Index() { return View(); } 我想读这样一个字符串: public virtual ActionResult Index(string name) { // call a service with the string name return View()

我需要使用MVC创建自定义路线以构建自定义搜索:

默认主索引的操作:

    public virtual ActionResult Index()
    {
        return View();
    }
我想读这样一个字符串:

    public virtual ActionResult Index(string name)
    {

        // call a service with the string name

        return View();
    }
对于以下URL:

www.company.com/name
问题是我有两条路线,但它不起作用:

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

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

这样,除Home之外的任何控制器都会重定向到Home,如果我切换顺序,它将找不到索引Home操作。

您可以使用属性路由进行此操作。您可以查看有关包的详细信息。安装属性路由包后。现在,MVC5应用程序默认安装了一天。更改您的操作方法,如下所示:

[GET("{name}")]
public virtual ActionResult Index(string name)
{

    // call a service with the string name

    return View();
}
[GET("{name}")]
public virtual ActionResult Index2(string name)
{

    // call a service with the string name

    return View("Index");
}
下面是上面代码的一个要点: 路由器也会将不带名称的请求发送到此操作方法。为了避免这种情况,您可以按以下方式进行更改:

[GET("{name}")]
public virtual ActionResult Index(string name)
{

    // call a service with the string name

    return View();
}
[GET("{name}")]
public virtual ActionResult Index2(string name)
{

    // call a service with the string name

    return View("Index");
}

嗨,谢谢,没有名字我不明白这个问题。我还需要打开没有名字的主页,可以吗?我也有一个WebApi,我应该知道使用该包时有什么吗?@Patrick如果您没有在路由中传递任何名称(在您的默认路由中),路由器将通过传递null name参数来点击第二个操作方法。这样做的缺点是,您必须将默认索引操作与之合并。你可以采用第二种方法,而不是那样做。除了网站上提到的一些高级功能外,属性路由包还可以与Web API一起使用。如果您为MVC项目安装它,web API就不必使用它。它仍然可以使用常规路由。嗨,但是如果Index2操作不在路由表中,它将如何找到它?我测试了它,它工作得很好。您不必将每个操作都放在路由表中。您可以使用路由表设置可接受的模式。如果我正确理解您发送的链接,您可以在这里阅读更多关于路由的内容,我不需要Index2,因为如果name为null,它将不会在操作索引中生成任何错误,对吗?