Usf Noor
Usf Noor

Reputation: 227

How to get the URL of a web API controller action method that is created in mvc project

I have created a mvc project, I have multiple mvc controller in my project, that are working fine. I have added a web API controller Cities as well in project under Controller folder.

Now I am unable to call it, actually i am unable to fine the url for this controller. I have added static WebApiConfig class in my project and call it in Application_Start method.

//application start.
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

//Register web api route
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

Web api controller:

    public class CitiesController : ApiController
    {
        CityEntities _entity = new CityEntities();

        // GET: api/Cities
        [HttpGet]
        public IEnumerable<City> Get()
        {
            return _entity.Cities.ToList();
        }

        // GET: api/Cities/5
        public City Get(int id)
        {
            return _entity.Cities.Where(x=>x.city_id==id).FirstOrDefault();
        }
    }

the URL that i did try to call Cities controller are.

But not work.

enter image description here

Upvotes: 0

Views: 2404

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

If you are not using attribute routing for that action, then action should map to default API route. Take a look at default route template for api routes:

api/{controller}/{id}

Things to consider:

  • This route has an api path segment. Thus your second url will not match default api route
  • This route does not have action parameter. That's because actions of ApiControllers are mapped by HTTP method of the request. You should not specify action name in request url. By convention, for HTTP GET requests name of action should begin with Get word.

So, your actions should be mapped to following HTTP GET requests:

GET http://localhost:56261/api/Cities
GET http://localhost:56261/api/Cities/5

Further reading: Routing in ASP.NET Web API

Upvotes: 2

Related Questions