Asp.net
Web api: 請求的資源不支持 http 方法 ‘GET’
我在 MVC4 項目上創建了一個 API 控制器
這是我為測試 API 功能而創建的方法
private string Login(int id) { Employee emp = db.Employees.Find(id); return emp.Firstname; }當我嘗試使用 訪問此 api 時
localhost:xxxx/api/controllerName/Login?id=2,我得到{"$id":“1”,“Message”:“請求的資源不支持 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); }
將方法修飾符從私有更改為公共,並將相關的接受動詞添加到操作中
private string Login(int id)改成:
[HttpGet] // Or [AcceptVerbs("GET", "POST")] public string Login(int id)
除了目前接受的添加
[HttpGet]屬性以使方法公開的答案之外,您還需要確保使用正確的命名空間:
- MVC 控制器使用
System.Web.Mvc- WebAPI 控制器使用
System.Web.Http