如果标头中指定的版本不存在,则返回400 Bad Request

时间:2014-04-20 05:38:13

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

我正在编写Web API,并且正在使用路由约束实现版本控制,类似于位于here的Web API 2示例中的操作方式。

我有一个类似于下面的IHttpRouteConstraint的实现。我注意到,如果我在请求中传递了一个不存在的版本,在为具有约束的route属性的每个Controller调用Match之后,将返回404。

我想在这种情况下返回一个不同的错误。可能是400,带有自定义消息。我不完全确定如何做到这一点。

所有这些网络内容对我来说都很新鲜。

修改:只是澄清一下。我遇到的问题是我不确定如何测试这种情况以及在哪里抛出/返回错误。

/// <summary>
/// A Constraint implementation that matches an HTTP header against an expected version value.
/// </summary>
internal class VersionConstraint : IHttpRouteConstraint
{
    public const string VersionHeaderName = "api-version";

    private const int DefaultVersion = 1;

    public VersionConstraint(int allowedVersion)
    {
        AllowedVersion = allowedVersion;
    }

    public int AllowedVersion
    {
        get;
        private set;
    }

    public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
    {
        if (routeDirection == HttpRouteDirection.UriResolution)
        {
            int version = GetVersionHeader(request) ?? DefaultVersion;
            if (version == AllowedVersion)
            {
                return true;
            }
        }

        return false;
    }

    private int? GetVersionHeader(HttpRequestMessage request)
    {
        string versionAsString;
        IEnumerable<string> headerValues;
        if (request.Headers.TryGetValues(VersionHeaderName, out headerValues) && headerValues.Count() == 1)
        {
            versionAsString = headerValues.First();
        }
        else
        {
            return null;
        }

        int version;
        if (versionAsString != null && Int32.TryParse(versionAsString, out version))
        {
            return version;
        }

        return null;
    }

1 个答案:

答案 0 :(得分:0)

您应该能够在Web Api中使用Request.CreateErrorResponse来返回自定义状态代码:

return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, 
                    new UnauthorizedAccessException("not Authorized."));

希望这有帮助。