UrlHelper.Link()返回null

时间:2014-06-17 09:32:52

标签: asp.net-web-api2 asp.net-web-api-routing

我知道这里有很多问题都有这个标题,但是,经过它们,我不相信任何发布的解决方案有帮助。

我在Web Api v2.1控制器中有以下代码......

    [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);
        }
    }

在分配了link的行之后的行上放置一个断点,我可以看到它是null。我还可以看到请求具有我期望看到的内容......

{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
}}

helper非空。

以下是VersionedRouteAttribute

的定义
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;
        }
    }
}

我相信,从我读过的所有内容来看,这应该有效。我只是无法弄清楚错误是什么。我很欣赏任何指示。

1 个答案:

答案 0 :(得分:3)

我相信您使用here中的RoutingConstraintsSample来演示使用属性路由进行版本控制...如果是,则该示例中的VersionConstraint有一个错误...您可以修改它的Match方法,如下所示:

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; 
}

另外,为什么要将UrlHelper自己实例化为已经由控制器上提供的Url属性提供给您的。{/ p>