我的应用程序中存在 URL 路由问题。我已经尝试解决这个问题,但没有真正取得任何进展。
因此,我在客户端发出以下 AJAX 请求:
$.ajax({
type: 'GET',
url: programState.getBaseUrl() + 'Playlist/GetPlaylistsByUserId',
dataType: 'json',
data: {
userId: user.get('id')
},
success: function (data) {
console.log("JSON data:", data);
},
error: function(error) {
console.error(error);
}
});
这是网络:
这是服务器错误:
这是 Controller 的 GET 和 GetPlaylistsByUserId 方法:
[HttpGet]
public ActionResult Get(Guid id)
{
Playlist playlist = PlaylistDao.GetById(id);
return new JsonDataContractActionResult(playlist);
}
[HttpGet, ActionName("GetPlaylistsByUserId")]
public ActionResult GetPlaylistsByUserId(Guid userId)
{
IList<Playlist> playlists = PlaylistDao.GetByUserId(userId);
return new JsonDataContractActionResult(playlists);
}
最后,这是我的路线:
routes.MapRoute(
"getPlaylistsByUserId",
"{controller}/{userId}",
new { controller = "Playlist", action = "GetPlaylistsByUserId" },
new { httpMethod = new HttpMethodConstraint("GET") }
);
routes.MapRoute(
"post-Playlist",
"{controller}",
new { controller = "Playlist", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
"get-Playlist",
"{controller}/{action}/{id}",
new { controller = "Playlist", action = "get" },
new { httpMethod = new HttpMethodConstraint("GET") }
);
routes.MapRoute(
"put-Playlist",
"{controller}",
new { controller = "Playlist", action = "update" },
new { httpMethod = new HttpMethodConstraint("PUT") }
);
routes.MapRoute(
"delete-Playlist",
"{controller}/{id}",
new { controller = "Playlist", action = "delete" },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
据我所知——我正在将我的 URL 路由到我的“获取”操作,但我打算将它路由到“GetPlaylistsByUserId”操作。我相信这会发生,因为服务器错误表明它正在为方法“Get”寻找参数“id”。
不过,我不确定为什么会发生这种情况,因为我似乎很清楚地计划了我的其他行动...?
最佳答案
将路由与请求进行比较 - 您请求的操作名称与路由不匹配。就目前而言,您的路由期望您的 ajax 请求转到 .../Playlist/SomeGuid
而不是 Playlist/GetPlaylistsByUserId?userId=SomeGuid
。
如果你想将所有对 Playlist
Controller 的请求路由到 GetPlaylistsByUserId 操作,如果没有指定操作,你想要的路由是:
routes.MapRoute(
"getPlaylistsByUserId",
"Playlist",
new { controller = "Playlist", action = "GetPlaylistsByUserId" },
new { httpMethod = new HttpMethodConstraint("GET") }
);
请注意省略了 userId - 这是作为查询字符串传递的,不需要包含在您的路由中。 MVC 将自动绑定(bind)它。
然而,就目前而言,您是请求一个 Action 名称,所以下面的路由将选择它:
routes.MapRoute(
"getPlaylistsByUserId",
"Playlist/{action}",
new { controller = "Playlist", action = "GetPlaylistsByUserId" },
new { httpMethod = new HttpMethodConstraint("GET") }
);
您也可以使用 {controller}/{action}
,但我猜您不希望所有 Controller 都默认执行名为 GetPlaylistsByUserId
的操作。
关于c# - MVC 将我的 GET 请求路由到错误的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528125/