I’ve just created asp.net mvc 4 app and added default webapi controller
public class UserApiController : ApiController
{
// GET api/default1
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/default1/5
public string Get(int id)
{
return "value";
}
// POST api/default1
public void Post(string value)
{
}
// PUT api/default1/5
public void Put(int id, string value)
{
}
// DELETE api/default1/5
public void Delete(int id)
{
}
}
Then i was trying to call method get() by typing http://localhost:51416/api/get in the browser but getting error:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:51416/api/get'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'get'.
</MessageDetail>
</Error>
my route config:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
//defaults: new { controller = "UserApiController", id = RouteParameter.Optional }
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Why it is not working by default?
What can i do in order to fix that?
You don’t need to put
getin the URL because GET is type of the HTTP verb.And by default the browsers sends GET request if you type in an URL.
So try it with
http://localhost:51416/api/Because
UserApiControlleris the default api controller if you uncomment the linedefaults: new { controller = "UserApiController"...in your routing configNote that you don’t need the “controller” suffix when specifying your routes so the correct
dafaultssettings is :defaults: new { controller = "UserApi", id = RouteParameter.Optional })
or you need to explicitly specifying the controller
http://localhost:51416/api/userapiYou can start learning about Wep.API and a HTTP verb based routing conventions on the ASP.NET Web API site.