Search code examples
c#asp.net-mvcasp.net-web-apihtml-helperasp.net-web-api-routing

HttpRouteUrl and Attribute Routing in WebAPI 2


I have the following controller which allows me to download a file via CSV using a URL that ends in /api/v1/report/123.csv:

[RoutePrefix("api/v{version:int?}/report")]
public class ReportController : ApiController
{
    // ...
    [Route("{id}.{ext}", Name="DownloadCsvReport")]
    public HttpResponseMessage Get(int id, String ext)
    {
       //...
    }
}

Are there any helpers that will construct the correct URL? I'm trying to link to the file in an MVC4.5 page but I don't seem to be able to get either the extension or the version:

@Url.HttpRouteUrl("DefaultApi", new { controller = "Report", ext="csv", version=1, id = 3, })

@Url.RouteUrl(routeName: "DownloadCsvReport", routeValues: new { id=123, version=1, ext = "csv"})

@Url.Action("DownloadCsvReport", new { id = 123, ext="csv" })

@Url.RouteUrl("DefaultApi", new { httproute = true, controller = "Report", id = 123, Ext="csv", version =1 })

I don't think I'm on the right track with any of these.... None of them substitute the version in the routeprefix or ext in the route attribute, plus various other problems. Is there any way to link to the URL without hardcoding the path?


Solution

  • Try the following:

    @Url.HttpRouteUrl("DownloadCsvReport", new { ext="csv", version=1, id = 3, })
    

    OR

    @Url.RouteUrl("DownloadCsvReport", new { httproute = true, id = 123, Ext="csv", version =1 })