2013-03-16 80 views
8

我對我的MVC4項目的Web API:請求的資源不支持HTTP方法「GET」

這裏創建了一個API控制器是我創建測試API

private string Login(int id) 
{ 
    Employee emp = db.Employees.Find(id); 
    return emp.Firstname; 
} 

的功能的方法當我試着使用localhost:xxxx/api/controllerName/Login?id=2訪問此API,我得到

{ 「的$ id」: 「1」, 「消息」: 「所請求的資源不支持HTTP方法 'GET'。」}

我在做什麼錯?

而且,這裏是我的API配置文件

public static void Register(HttpConfiguration config) 
    { 
     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     var json = config.Formatters.JsonFormatter; 
     json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; 
     config.Formatters.Remove(config.Formatters.XmlFormatter); 
    } 
+2

開始使該方法公開 – 2013-03-16 22:45:13

+3

@GiorgioMinardi,繼續'[HttpGet] //或[AcceptVerbs(「GET」,「POST」)]'... – gdoron 2013-03-16 22:47:15

+0

@giorgio Minardi,@ gdoron哦。多謝你們。我的錯。所以很抱歉用這麼瑣碎的東西來打擾社區。它現在可行,但我期待它能給我帶來d格式的「名字:約翰」。它只是給「約翰」。這是正常的行爲? – ylinkz 2013-03-16 23:15:48

回答

19

變化,從私人的方法修改爲public,還加了有關接受動詞的動作

private string Login(int id) 

更改爲:

[HttpGet] // Or [AcceptVerbs("GET", "POST")] 
public string Login(int id) 
+0

謝謝@gdoron – ylinkz 2013-03-16 23:17:06

+0

我的方法被分類爲「公共」,但我仍然面臨這個錯誤。 – Vijayaraghavan 2018-01-18 09:49:25

+0

@Vijayaraghavan發佈您的代碼,如果沒有人幫助,您可以ping我。我相信你會在幾分鐘內得到答案。 – gdoron 2018-01-18 12:23:43

3

你也可以在web.config裏面接受system.webserver標記中的http方法:

<httpProtocol> 
    <customHeaders> 
     <clear /> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
     <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" /> 
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> 
    </customHeaders> 
</httpProtocol> 
+0

我不確定這與問題有關。 這些標題將CORS信息添加到響應中。 它們指定在執行CORS請求時可能允許客戶端使用哪些HTTP方法。然而,MVC方法在服務器端進行管理。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – 2016-05-09 09:00:35

1

除了加入[HttpGet]屬性,使方法public目前公認的答案,你需要確保你使用了正確的命名空間:

  • MVC控制器使用System.Web.Mvc
  • WebAPI控制器使用System.Web.Http
相關問題