Routing with multiple Get methods in ASP.NET Web API

前端 未结 10 792
闹比i
闹比i 2020-11-27 10:13

I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get meth

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 10:43

    After reading lots of answers finally I figured out.

    First, I added 3 different routes into WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
    
        // Web API routes
        config.MapHttpAttributeRoutes();
    
        config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );
    
        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );
    
        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
    }
    

    Then, removed ActionName, Route, etc.. from the controller functions. So basically this is my controller;

    // GET: api/Countries/5
    [ResponseType(typeof(Countries))]
    //[ActionName("CountryById")]
    public async Task GetCountries(int id)
    {
        Countries countries = await db.Countries.FindAsync(id);
        if (countries == null)
        {
            return NotFound();
        }
    
        return Ok(countries);
    }
    
    // GET: api/Countries/tur
    //[ResponseType(typeof(Countries))]
    ////[Route("api/CountriesByName/{anyString}")]
    ////[ActionName("CountriesByName")]
    //[HttpGet]
    [ResponseType(typeof(Countries))]
    //[ActionName("CountryByName")]
    public async Task GetCountriesByName(string name)
    {
        var countries = await db.Countries
                .Where(s=>s.Country.ToString().StartsWith(name))
                .ToListAsync();
    
        if (countries == null)
        {
            return NotFound();
        }
    
        return Ok(countries);
    }
    

    Now I am able to run with following url samples(with name and with id);

    http://localhost:49787/api/Countries/GetCountriesByName/France

    http://localhost:49787/api/Countries/1

提交回复
热议问题