Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web api: The requested resource does not support http method 'GET'

I created an API controller on my MVC4 project

Here is the method I created to test the functionality of the API

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

When I try to access this api with localhost:xxxx/api/controllerName/Login?id=2, I get

{"$id":"1","Message":"The requested resource does not support http method 'GET'."}

What am I doing wrong?

Also, here is my api config file

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);
    }
like image 509
ylinkz Avatar asked Mar 16 '13 22:03

ylinkz


2 Answers

In addition to the currently accepted answer of adding the [HttpGet] attribute to make the method public, you need to make sure you are using the right namespace:

  • MVC controllers use System.Web.Mvc
  • WebAPI controllers use System.Web.Http
like image 114
Jay bennie Avatar answered Sep 20 '22 15:09

Jay bennie


Change the method modifier from private to public, also add the relevant accept verbs to the action

private string Login(int id)

Change to:

[HttpGet] // Or [AcceptVerbs("GET", "POST")]
public string Login(int id)
like image 44
gdoron is supporting Monica Avatar answered Sep 20 '22 15:09

gdoron is supporting Monica