ASP MVC5 方法未命中
ASP MVC5 Method not hit
我的 EventsController 中有一个方法,其定义如下:
public JsonResult Index(string id)
{
...
}
当我尝试使用 http://localhost:57715/events/some_string , I cannot reach it. But when I browse to http://localhost:57715/events 从浏览器访问它时,我的调试点被命中并且 id 为空。这是为什么?我的路由定义如下(我没改):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我设法解决了它,这是一件简单的事情。我应该使用 http://localhost:57715/events/Index/some_string
而不是使用 http://localhost:57715/events/some_string
当您请求 http://localhost:57715/events/some_string
时,MVC 框架不知道 some_string
是一个操作方法名称或 id 参数值。所以你应该明确指定参数名称。
这应该有效
http://localhost:57715/events?id=some_string
或 你可以使用 url 它有控制器名称和操作方法名称以及你的 id 参数值
http://localhost:57715/events/yourActionMethodName/some_string
如果您绝对希望 url yourSite/events/some_string
正常工作,您可以考虑启用属性路由并在您的操作方法中指定上述路由模式,如下所示
public class EventsController : Controller
{
[Route("Events/{id}")]
public ActionResult Index(string id)
{
return Content("id : "+id);
}
}
现在请求 yourSite/events/some_string
将由 EventsController 的索引操作方法处理。
我的 EventsController 中有一个方法,其定义如下:
public JsonResult Index(string id)
{
...
}
当我尝试使用 http://localhost:57715/events/some_string , I cannot reach it. But when I browse to http://localhost:57715/events 从浏览器访问它时,我的调试点被命中并且 id 为空。这是为什么?我的路由定义如下(我没改):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我设法解决了它,这是一件简单的事情。我应该使用 http://localhost:57715/events/Index/some_string
http://localhost:57715/events/some_string
当您请求 http://localhost:57715/events/some_string
时,MVC 框架不知道 some_string
是一个操作方法名称或 id 参数值。所以你应该明确指定参数名称。
这应该有效
http://localhost:57715/events?id=some_string
或 你可以使用 url 它有控制器名称和操作方法名称以及你的 id 参数值
http://localhost:57715/events/yourActionMethodName/some_string
如果您绝对希望 url yourSite/events/some_string
正常工作,您可以考虑启用属性路由并在您的操作方法中指定上述路由模式,如下所示
public class EventsController : Controller
{
[Route("Events/{id}")]
public ActionResult Index(string id)
{
return Content("id : "+id);
}
}
现在请求 yourSite/events/some_string
将由 EventsController 的索引操作方法处理。