I have a WebAPI controller named WeatherForecast with one operation. The operation method looks like follow:
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
However, the HttpGet.Name = "GetWeatherForecast"
should define a route name "GetWeatherForecast" as I understand the purpose of the Name
property for this attribute.
But Swagger shows me that the operation itself has no route at all:
The displayed URL is https://localhost:port/WeatherForecast
(the service operation can be consumed through that URL, I used Postman for testing)
But with the HttpGet
attribute with the Name
property set, I would expect it to be https://localhost:port/WeaterhForecast/GetWeatherForecast
When I additionally use the Route
attribute (Route("GetWeatherForecast")
) on the operation method, then the route for the operation is shown as follows: https://localhost:port/WeaterhForecast/GetWeatherForecast
(the service operation is indeed now accessible through that URL).
So, the question is: Why is the Name
property of HttpGet
attribute not doing what documentation promised? Or what is HttpGetAttribute.Name
really for?
The source code was made with .NET 6.0 with VS 2022, project type ASP.NET Core-Web-API. The shown code is from the automatically created controller by project template.
2
Answers
The way you have used the
HttpGet
attribute:Means you are specifying the
Name
property which doesn’t change how the URL for the route is generated. The route name can be used to generate a link using a specific route, instead of relying on the selection of a route based on the given set of route values.Instead, you should specify the
Template
property, either by excluding the named parameter or using the correct name:Or:
DavidG is right. using [HttpGet("GetWeatherForecast")] instead of [HttpGet(Name = "GetWeatherForecast")] works for me. I was stuck on the same issue for many days, tried a lot of work arounds and followed almost all of the suggestions available on the internet in different forums but the solution which worked like a charm was to remove the Name attribute inside your controller.
This is indeed a strange fact that using [HttpGet(Name = "GetWeatherForecast")] does work as it implies it will do and if you use something like
it also does not work like that….