简体   繁体   中英

MVC Core overriding routing breaks Url.RouteUrl helper method when using aspnet-api-versioning

In a MVC Core web app, using the "~" to override the route prefix on a controller method seems to break the Url.RouteUrl helper method. It returns null instead of the proper route.

Example:

[Route("v{api-version:apiVersion}/[controller]")]
public class BooksController : ApiController
{
    [HttpGet]
    [Route("{bookId}", Name = "GetBook")]
    public Book GetBook( int bookId )
    {
    }

    // GET /v1/authors/1/books
    [HttpGet]
    [Route("~/v{api - version:apiVersion}/authors/{authorId:int}/books")]
    public IEnumerable<Book> GetByAuthor(int authorId)
    {
        // do some stuff
        string route = Url.RouteUrl( "GetBook", new { id = 1 });
    }
}

I believe the above example will show the problem. The route returned from Url.RouteUrl() is null. Without using versioning, and removing the "" from the routes, the RouteUrl() method will properly return the url to the GetBook method. Its the addition of the aspnet-api-versioning nuget package that's causing the problem somehow.

Any ideas how to get RouteUrl to work in this instance?

Ok, stumbled upon an answer for this. Not sure why this fixed the problem, but changing route from:

[Route("~/v{api - version:apiVersion}/authors/{authorId:int}/books")]

to:

[Route("~/v{version:apiVersion}/authors/{authorId:int}/books")]

fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM