簡體   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