Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing doesn't work without attributes

EDIT: An issue has been opened on GitHub to clarify the docs with the information in the answer.

I'm trying to set up routing in my .NET Core MVC app (for an API). I believe I have everything configured correctly, but no routes work (all return 404) unless the action has a routing attribute explicitly set. This same problem is mentioned here, but he doesn't know what fixed the problem.

I put the attributes back on, it worked. I removed them, it didn't. Eventually through some magical incantation of removing and re-adding route configuration - switching it off and back on again in other words - UseMvcWithDefaultRoute() worked without routing attributes. Not sure what happened there.

Here is a simplified version of what I have. What's the problem? Why isn't routing working without attributes set?

In this example, I'm attempting to POST to /login/register.

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    })
        .AddJsonOptions(options =>
            options.SerializerSettings.ContractResolver = 
                new CamelCasePropertyNamesContractResolver());

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
}

I also tried specifying the route manually:

app.UseMvc(routes =>
{
    routes.MapRoute(
        "default",
        "{controller=Home}/{action=Index}/{id?}");
});

Login controller:

[Route("[controller]")]
[AllowAnonymous]
public class LoginController : Controller
{
    [HttpPost]
    [Route("register")] // only works with this here
    public IActionResult Register([FromBody]RegisterModel model)
    {
        return Ok();
    }
}
like image 750
vaindil Avatar asked Aug 18 '16 01:08

vaindil


People also ask

Why do we need attribute routing?

Routing is how Web API matches a URI to an action. 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 difference between attribute and conventional routing?

As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.

Is conventional routing and attribute routing can work together?

As shown in the preceding code, attribute routing may be combined with convention-based routing in Web API apps. In addition to attribute routing, ASP.NET Web API chooses which action to call based on the HTTP method (for example, GET or POST), the {action} placeholder in a route (if any), and parameters of the action.

How do I enable attribute routing?

Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes. MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig. cs file. You can also combine attribute routing with convention-based routing.


1 Answers

The default {controller=Home}/{action=Index}/{id?} route will already map the controller and action to /Login/Controller. However, if you add a [Route] attribute on the controller, you indicate that you want to start building a new route and the default route will not apply anymore. Therefore you'll either have to remove the attributes from both the controller and action or add it to both. You might also want to use the [action] route token as well:

[Route("[controller]/[action]")]
[AllowAnonymous]
public class LoginController : Controller
{
   // ...
}
like image 139
Henk Mollema Avatar answered Sep 20 '22 21:09

Henk Mollema