繁体   English   中英

ASP.NET Web API-尝试传递参数时不支持GET HTTP Verb(405)

[英]ASP.NET Web API - GET HTTP Verb not supported (405) when attempting to pass a parameter

我尝试使用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的知识了解不多-我主要遵循Microsoft的指南,位于此处(docs.microsoft.com)

如果有人有任何想法,我将不胜感激。 我已经看过很多关于此的问题,但没有一个有帮助。

我尝试将[HTTPGet]添加到GetComment(int id)方法中,以及使用[Route]指定路由,但我GetComment(int id)

任何帮助将非常感激。 谢谢。

您的路线配置可能与您的网址不匹配。

路由配置: 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';

可以匹配您的路线设置。

只需在浏览器中尝试url = 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;

希望对您有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM