Search code examples
c#asp.netcontroller

Why second controller doesn't work in asp.net webApi?


I would like to have second controller in my asp.net WebApi, but when i add it it not works... First Controller works OK

i have 404 not found in my browser

  • not any errors while run

whats wrong?

namespace testing.Controllers
   {
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering",           
   "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

and the second is below

{
    [Route("[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public int Get()
        {
            return 100050;
        }
    }
}

Can some one tell me whats wrong?


Solution

  • You're using the attribute [Route("[controller]")] on your controller class. The string [controller] means "the name of the class, without the actual WORD "Controller".

    This means, the name of the controller is "Values" (or "WeatherForecast" for the previous controller).

    So, the final url route you want is /Values, not /ValuesController.

    You can read more about how this works on the MS Docs page (the whole page has a lot of good information, not just that section).