使用路由属性在 asp.net mvc 中调用操作的两种方式 - Routing In asp.net mvc
Tow way for call a action in asp.net mvc with route attribute - Routing In asp.net mvc
全部
我想要 2 种调用操作的方式。例如
http://localhost:16800/Content1/1/text
和
http://localhost:16800/Content1/1
我的路由配置是默认路由。我使用 from 路由属性 .
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我的控制器使用了路由属性,所以:
namespace WebApplication2.Controllers
{
[RoutePrefix("Content1")]
[Route("{action=Index}")]
public class Content1Controller : Controller
{
[Route("{id}/{text}")]
public ActionResult Index(int id, string text)
{
return View();
}
}
}
现在,这种方式对我有用。 http://localhost:16800/Content1/1/text
而且这种方式对我不起作用。 http://localhost:16800/Content1/1
我只是用这两种方式来调用我的操作。
提醒我在我的控制器上使用 [Route("{action=Index}")]
,我不需要在我的 url 中定义动作名称。
Try this, It will work(tested).
namespace WebApplicationExamples.Controllers
{
[RoutePrefix("Content1")]
[Route("{action=Index}")]
public class Content1Controller : Controller
{
// GET: Content1
[Route("{id}")]
[Route("{id}/{text}")]
public ActionResult Index()
{
return View();
}
}
}
全部 我想要 2 种调用操作的方式。例如
http://localhost:16800/Content1/1/text
和
http://localhost:16800/Content1/1
我的路由配置是默认路由。我使用 from 路由属性 .
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我的控制器使用了路由属性,所以:
namespace WebApplication2.Controllers
{
[RoutePrefix("Content1")]
[Route("{action=Index}")]
public class Content1Controller : Controller
{
[Route("{id}/{text}")]
public ActionResult Index(int id, string text)
{
return View();
}
}
}
现在,这种方式对我有用。 http://localhost:16800/Content1/1/text
而且这种方式对我不起作用。 http://localhost:16800/Content1/1
我只是用这两种方式来调用我的操作。
提醒我在我的控制器上使用 [Route("{action=Index}")]
,我不需要在我的 url 中定义动作名称。
Try this, It will work(tested).
namespace WebApplicationExamples.Controllers
{
[RoutePrefix("Content1")]
[Route("{action=Index}")]
public class Content1Controller : Controller
{
// GET: Content1
[Route("{id}")]
[Route("{id}/{text}")]
public ActionResult Index()
{
return View();
}
}
}