Reputation: 1663
I know that there are a number of questions here that have this title, but, having been through them, I do not believe any of the posted solutions help.
I have the following code in a Web Api v2.1 Controller...
[VersionedRoute("{id:int}", 1, Name="GetEvent")]
[HttpGet]
public IHttpActionResult Get(int id)
{
try
{
var helper = new UrlHelper(Request);
var link = helper.Link("GetEvent", new { id = id });
var result = ApiBL.V1Get(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
catch (Exception ex)
{
throw new ApiHttpResponseException(HttpStatusCode.BadRequest, ex);
}
}
Putting a breakpoint on the line after the line on which link
is assigned, I can see that it is null. I can also see that Request has what I'd expect to see...
{Method: GET, RequestUri: 'http://localhost:8087/atlas/api/events/50', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Authorization: Basic blahblahblah
Host: localhost:8087
Content-Length: 31
Content-Type: application/json
}}
And that helper
is non-null.
Below is the definition of the VersionedRouteAttribute
class
public class VersionedRouteAttribute : RouteFactoryAttribute
{
public VersionedRouteAttribute(string template, int allowedVersion)
: base(template)
{
AllowedVersion = allowedVersion;
}
public int AllowedVersion { get; private set; }
public override IDictionary<string, object> Constraints
{
get
{
var constraints = new HttpRouteValueDictionary();
constraints.Add("version", new VersionConstraint(AllowedVersion));
return constraints;
}
}
}
I believe, from everything I've read, that this should work. I simply can't figure out what's wrong. I'd appreciate any pointers.
Upvotes: 2
Views: 2978
Reputation: 57939
I believe you are using the RoutingConstraintsSample
from here which demonstrates versioning with attribute routing...if yes, then the VersionConstraint
in that sample has a bug...you can modify the Match
method of that to like below:
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (routeDirection == HttpRouteDirection.UriResolution)
{
int version = GetVersionHeader(request) ?? DefaultVersion;
return (version == AllowedVersion);
}
return true;
}
Also why are you instantiating UrlHelper
yourself as its already provided to you by the Url
property that is available on the controller.
Upvotes: 3