Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API 2 RoutePrefix does not working

When defining a RoutePrefix at controller level, when I try to access the API class using the URL with prefix http://localhost:55020/api/v2/dummy/get it throws 404. This http://localhost:55020/api/dummy/get works absolutely fine though.

Here is controller class which has a RoutePrefix defined

    [RoutePrefix("v2/dummy")]
    public class DummyController : ApiController
    {
        // GET api/values
        [SwaggerOperation("Get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2", "value3" };
        }
    }

Here is WebApiConfig

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
like image 468
Vikram Avatar asked Oct 17 '16 08:10

Vikram


People also ask

What is RoutePrefix in Web API?

The RoutePrefix attribute is used to specify the common route prefix at the controller level to eliminate the need to repeat the common route prefix on each and every controller action.

Which of the following types of routing is supported in Web API 2?

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

What is route prefix?

Route prefixes are associated with routes by design in attribute routing. It is used to set a common prefix for an entire controller. If you read the release notes that introduced the feature you may get a better understanding of the subject.

What is attribute routing in asp net core?

Summary. Attribute routing in ASP.NET Core 3.0 allows us to define specific, customized routes for actions in our systems. Said routes are applied directly at the controller action level, allowing for high cohesion between route and action.


1 Answers

Use attribute routing instead

public class DummyController : ApiController
{
    // GET api/values
    [HttpGet]
    [Route("api/v2/dummy/get")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2", "value3" };
    }
}

and if you want route prefix then

[RoutePrefix("api/v2/dummy")]
public class DummyController : ApiController
{
    // GET api/v2/dummy
    [HttpGet]
    [Route("get")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2", "value3" };
    }
}
like image 172
Mostafiz Avatar answered Oct 01 '22 15:10

Mostafiz