Reputation: 301
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);
}
Upvotes: 12
Views: 77520
Reputation: 31
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:
System.Web.Mvc
System.Web.Http
Upvotes: 3
Reputation: 5217
You can also accept http methods in web.config inside system.webserver tag:
<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>
Upvotes: 3
Reputation: 150243
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)
Upvotes: 23