【问题标题】:Rewriting the URL for a Controllers Action Method重写控制器操作方法的 URL
【发布时间】:2010-11-22 19:02:42
【问题描述】:

我有一个名为 Person 的控制器,它有一个名为 NameSearch 的 post 方法。

此方法返回 RedirectToAction("Index"),或 View("SearchResults"),或 View("Details")。 我为所有 3 种可能性获得的网址是 http://mysite.com/Person/NameSearch。 我将如何更改它以将 URL 重写为 http://mysite.com/Person/Index 用于 RedirectToAction("Index")、http://mysite.com/Person/SearchResults 用于 View("SearchResults") 和 http://mysite.com/Person/Details 用于 View("Details")。

提前致谢

【问题讨论】:

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


    【解决方案1】:

    我假设您的 NameSearch 函数评估查询结果并根据以下条件返回这些结果:

    1. 查询有效吗?如果没有,请返回索引。
    2. 结果中是否有 0 或 >1 个人,如果有,请发送到搜索结果
    3. 如果结果中正好有 1 个人,请发送至详细信息。

    所以,你的控制器看起来更像:

    public class PersonController
    {
      public ActionResult NameSearch(string name)
      {
        // Manage query?
        if (string.IsNullOrEmpty(name))
          return RedirectToAction("Index");
    
        var result = GetResult(name);
        var person = result.SingleOrDefault();
        if (person == null)
          return RedirectToAction("SearchResults", new { name });
    
        return RedirectToAction("Details", new { id = person.Id });
      }
    
      public ActionResult SearchResults(string name)
      {
        var model = // Create model...
    
        return View(model);
      }
    
      public ActionResult Details(int id)
      {
        var model= // Create model...
    
        return View(model);
      }
    }
    

    因此,您可能需要这样定义路由:

    routes.MapRoute(
      "SearchResults",
      "Person/SearchResults/{name}",
      new { controller = "Person", action = "SearchResults" });
    
    routes.MapRoute(
      "Details",
      "Person/Details/{id}",
      new { controller = "Person", action = "Details" });
    

    Index 动作结果将由默认的{controller}/{action}/{id} 路由处理。

    这会让你朝着正确的方向前进?

    【讨论】:

    • 谢谢马修!这正是我一直在寻找的方向!
    • 您能否用您的控制器实际外观的摘录以及您的路线(以及它们的注册顺序)来更新问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2018-10-14
    • 2018-01-22
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多