Web api:请求的资源不支持http方法'GET'

yli*_*nkz 10 asp.net asp.net-mvc json asp.net-web-api

我在MVC4项目上创建了一个API控制器

这是我为测试API功能而创建的方法

private string Login(int id)
{
    Employee emp = db.Employees.Find(id);
    return emp.Firstname;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试访问此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);
    }
Run Code Online (Sandbox Code Playgroud)

gdo*_*ica 22

将方法修饰符从private更改为public,还将相关的accept动词添加到action

private string Login(int id)
Run Code Online (Sandbox Code Playgroud)

改成:

[HttpGet] // Or [AcceptVerbs("GET", "POST")]
public string Login(int id)
Run Code Online (Sandbox Code Playgroud)