Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HttpGetAttribute name property not working for routing

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

The way you have used the HttpGet attribute:

[HttpGet(Name = "GetWeatherForecast")]

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:

[HttpGet("GetWeatherForecast")]

Or:

[HttpGet(Template = "GetWeatherForecast")]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading