【问题标题】:mixing asp.net and MVC web application [duplicate]混合asp.net和MVC Web应用程序[重复]
【发布时间】:2015-08-10 15:32:25
【问题描述】:

我有一个在 asp.net webform 应用程序中运行的网站。目前我们计划将此 Webform 应用程序转换为 MVC,并满足以下条件。

  1. 仅新模块将以 MVC 模式开发。
  2. 现有模块将保留在 aspx 页面中。 (未转换为 MVC)。
  3. 主页将是 (default.aspx)

例如www.example.com 将指向www.example.com/default.aspx

将要开发的新模块将具有以下参数。

 www.example.com/place/Japan
 www.example.com/place/USA
 www.example.com/place/(anycountry)

所以我开发了一个名为 place 的控制器。

代码:

  public class PlaceController : Controller
  {
    //
    // GET: /Place/
      [HttpGet]
    public ActionResult Index()
    {

        return View();
    }

   public ActionResult Index(string country)
      {

          return View();
      }

当我输入以下 URL 时: http://example.com/ 转到http://example.com/default.aspx

我的路由配置有:

 routes.MapRoute("Default", "{controller}/{action}/{id}", new { id = UrlParameter.Optional });

但是当我添加以下内容时

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

并输入 www.example.com 它会转到放置控制器,而不是转到 default.aspx 页面。我将如何解决这个问题

如果我输入 www.example.com/place/japan 我也会得到 resource not found。我应该如何修改索引操作结果?

【问题讨论】:

  • 尝试将第二个 mapRoute 修改为 url: "Place/{action}/{id}", 并将其放在另一个 mapRoute 之前
  • @I19 成功了,谢谢。现在我将如何将 Index() 操作结果指向 www.example.com/place/countryname

标签: asp.net asp.net-mvc


【解决方案1】:

您不能有两个名为 way ("Index") 的操作并且都响应 GET 请求,因为 MVC 不知道要使用哪一个 (edit: 除非你用[HttpGet] 装饰一个。这将优先于另一个)。

因此,在您的控制器中,您需要将带有“country”参数的控制器重命名为“IndexByCountry”。然后试试这个:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        name: "Place",
        url: "Place/",
        defaults: new { controller = "Place", action = "Index" }
        );

    routes.MapRoute(
        name: "PlaceByCountry",
        url: "Place/{country}",
        defaults: new { controller = "Place", action = "IndexByCountry", country = "" }
        );
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { id = UrlParameter.Optional });
}

【讨论】:

  • 如果我输入 www.example.com/place/japan 我也找不到资源。我应该如何修改索引操作结果?
  • @Venkat 那是因为您没有指定名为Japan 的操作。你应该这样称呼它www.example.com/place/index?country=japan
  • 但这是一种通过 www.example.com/place(action-name)/japan(输入参数)实现相同目标的方法吗?我已准备好进行更改以适应这一点。
  • 你应该在一个单独的问题中问这个问题,但是是的,这是可能的。您需要添加一条新路由:url: "Place/{country}/"
  • 哦,对不起,我会编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
相关资源
最近更新 更多