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?
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.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
Attribute Routing The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method. Consider the following example of attribute routing.
In short, Convention Routing approaches Routing from the general case; you generally add some routes that will match all or most of your URLs, then add more specific routes for more specialized cases. The other way to approach this problem is via Attribute Routing.
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With