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?
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.
Yes, you can call a method of another controller. The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.
You don't need to put get
in 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 UserApiController
is the default api controller if you uncomment the line defaults: new { controller = "UserApiController"...
in your routing config
Note that you don't need the "controller" suffix when specifying your routes so the correct dafaults
settings is :defaults: new { controller = "UserApi", id = RouteParameter.Optional }
)
or you need to explicitly specifying the controller http://localhost:51416/api/userapi
You can start learning about Wep.API and a HTTP verb based routing conventions on the ASP.NET Web API site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With