我试图用getJSON请求调用我的Web API:
var uri = 'api/comment';
var id = solicitorId;
$.getJSON(uri, id, (function (data) {
$('#commentTableContainer').html(data);
}));
这是注释Controller类中的方法:
public string GetComment(int id)
{
//Do things
}
我正在使用默认路由:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
但是,当尝试使用getJSON调用api时,我收到405错误:
HTTP405: BAD METHOD - The HTTP verb used is not supported.
(XHR)GET - http://localhost:<port>/api/comment?334203
如果我从GetComment签名中删除id
参数,即GetComment()
,则GET请求有效
我不太了解这个WebAPI的东西 - 我大多数都遵循微软的指南,这里是here (docs.microsoft.com)
如果有人有任何想法,我将不胜感激。我已经看了很多这方面的问题,但没有一个有帮助。
我已经尝试将[HTTPGet]
添加到CommentController GetComment(int id)
方法,以及使用[Route]
指定路由但我无处可去。
任何帮助将非常感激。谢谢。
您的Route配置可能与您的URL不匹配。
路线配置:url: "{controller}/{action}/{id}"
请求网址:/api/comment?334203
您可以尝试添加Route
属性来为您的API操作设置RouteAttribute。
[Route("api/comment/{id}")]
[HttpGet]
public string GetComment(int id)
{
//Do things
}
你需要在你的ajax请求上使用完整的URL。
var uri = 'http://localhost:<port>/api/comment/GetComment';
可以匹配您的路线设置。
只需在浏览器中尝试网址= http://localhost:/ api / comment / GetComment?334203。也许你错过了URL中的方法名称。
此外,webApi.Config用于Web API。如果它不起作用,请告诉我。
非常感谢你的帮助。我现在修好了。我真的不知道如何描述这个,但我改变了我的$.getJSON
调用:
var uri = 'api/comment/' + id;
$.getJSON(uri, (function (data) {
//immaterial things
}
而我的CommentController方法回到public string GetComment(int id)
没有[Route]
或[HTTPGet]
它现在有效。我以为我以前曾尝试过这个,但没有。没有每个人的建议,我都无法解决这个问题,所以非常感谢你,周末愉快!
首先更改WebApiConfig文件并编辑默认路由,如下所示。
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
更改路径模板并添加“{action}”参数时,这意味着您必须在要调用操作时添加操作名称
然后你可以调用下面的url函数
var uri = 'http://localhost:<port>/api/comment/GetComment/'+id;
我希望这对你有帮助