Skip to content

Handle Ambiguous API Versions #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ApiVersioning.sln
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{261B77
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Versioning", "Versioning", "{DE4EE45F-F8EA-4B32-B16F-441F946ACEF4}"
ProjectSection(SolutionItems) = preProject
src\Common\Versioning\AmbiguousApiVersionException.cs = src\Common\Versioning\AmbiguousApiVersionException.cs
src\Common\Versioning\ApiVersioningOptions.cs = src\Common\Versioning\ApiVersioningOptions.cs
src\Common\Versioning\ApiVersionModel.cs = src\Common\Versioning\ApiVersionModel.cs
src\Common\Versioning\ApiVersionModelDebugView.cs = src\Common\Versioning\ApiVersionModelDebugView.cs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>4129</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:25282/</IISUrl>
<IISUrl>http://localhost:4129/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
Expand Down
18 changes: 18 additions & 0 deletions src/Common/CollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ namespace Microsoft.AspNetCore.Mvc
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Versioning;
using static System.Globalization.CultureInfo;
using static System.String;

internal static partial class CollectionExtensions
{
Expand Down Expand Up @@ -58,5 +61,20 @@ internal static void AddRange<T>( this ICollection<T> collection, IEnumerable<T>
collection.Add( item );
}
}

internal static string EnsureZeroOrOneApiVersions( this ICollection<string> apiVersions )
{
Contract.Requires( apiVersions != null );

if ( apiVersions.Count < 2 )
{
return apiVersions.SingleOrDefault();
}

var requestedVersions = Join( ", ", apiVersions.OrderBy( v => v ) );
var message = Format( InvariantCulture, SR.MultipleDifferentApiVersionsRequested, requestedVersions );

throw new AmbiguousApiVersionException( message, apiVersions.OrderBy( v => v ) );
}
}
}
78 changes: 78 additions & 0 deletions src/Common/Versioning/AmbiguousApiVersionException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#if WEBAPI
namespace Microsoft.Web.Http.Versioning
#else
namespace Microsoft.AspNetCore.Mvc.Versioning
#endif
{
using System;
using System.Collections.Generic;
using System.Linq;
#if NET451 || WEBAPI
using System.Runtime.Serialization;
#endif

/// <summary>
/// Represents the exception thrown when multiple, different API versions specified in a single request.
/// </summary>
#if NET451 || WEBAPI
[Serializable]
#endif
public class AmbiguousApiVersionException : Exception
{
private readonly string[] apiVersions;

/// <summary>
/// Initializes a new instance of the <see cref="AmbiguousApiVersionException"/> class.
/// </summary>
/// <param name="message">The associated error message.</param>
/// <param name="apiVersions">The <see cref="IEnumerable{T}">sequence</see> of ambiguous API versions.</param>
public AmbiguousApiVersionException( string message, IEnumerable<string> apiVersions )
: base( message )
{
Arg.NotNull( apiVersions, nameof( apiVersions ) );
this.apiVersions = apiVersions.ToArray();
}

/// <summary>
/// Initializes a new instance of the <see cref="AmbiguousApiVersionException"/> class.
/// </summary>
/// <param name="message">The associated error message.</param>
/// <param name="apiVersions">The <see cref="IEnumerable{T}">sequence</see> of ambiguous API versions.</param>
/// <param name="innerException">The inner <see cref="Exception">exception</see> that caused the current exception, if any.</param>
public AmbiguousApiVersionException( string message, IEnumerable<string> apiVersions, Exception innerException )
: base( message, innerException )
{
Arg.NotNull( apiVersions, nameof( apiVersions ) );
this.apiVersions = apiVersions.ToArray();
}

/// <summary>
/// Gets a read-only list of the ambiguous API versions.
/// </summary>
/// <value>A <see cref="IReadOnlyList{T}">read-only list</see> of unparsed, ambiguous API versions.</value>
public IReadOnlyList<string> ApiVersions => apiVersions;
#if NET451 || WEBAPI
/// <summary>
/// Initializes a new instance of the <see cref="AmbiguousApiVersionException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo">serialization info</see> the exception is being deserialized with.</param>
/// <param name="context">The <see cref="StreamingContext">streaming context</see> the exception is being deserialized from.</param>
protected AmbiguousApiVersionException( SerializationInfo info, StreamingContext context )
: base( info, context )
{
apiVersions = (string[]) info.GetValue( nameof( apiVersions ), typeof( string[] ) );
}

/// <summary>
/// Gets information about the exception being serialized.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo">serialization info</see> the exception is being serialized with.</param>
/// <param name="context">The <see cref="StreamingContext">streaming context</see> the exception is being serialized in.</param>
public override void GetObjectData( SerializationInfo info, StreamingContext context )
{
base.GetObjectData( info, context );
info.AddValue( nameof( apiVersions ), apiVersions );
}
#endif
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
namespace Microsoft.Web.OData.Routing
{
using Http;
using Http.Versioning;
using Microsoft.OData.Core;
using Microsoft.OData.Edm;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
Expand All @@ -11,6 +13,7 @@
using System.Web.OData.Routing;
using System.Web.OData.Routing.Conventions;
using static Http.ApiVersion;
using static System.Net.HttpStatusCode;
using static System.StringSplitOptions;
using static System.Web.Http.Routing.HttpRouteDirection;

Expand Down Expand Up @@ -85,6 +88,22 @@ private static bool TryExtractApiVersionFromSegment( string segment, out ApiVers
return TryParse( text, out apiVersion );
}

private static ApiVersion ResolveApiVersion( HttpRequestMessage request, IHttpRoute route )
{
Contract.Requires( request != null );
Contract.Requires( route != null );

try
{
return request.GetRequestedApiVersion() ?? GetApiVersionFromRoutePrefix( request, route );
}
catch ( AmbiguousApiVersionException ex )
{
var error = new ODataError() { ErrorCode = "AmbiguousApiVersion", Message = ex.Message };
throw new HttpResponseException( request.CreateResponse( BadRequest, error ) );
}
}

/// <summary>
/// Gets the API version matched by the current OData path route constraint.
/// </summary>
Expand All @@ -111,7 +130,7 @@ public override bool Match( HttpRequestMessage request, IHttpRoute route, string
return false;
}

var requestedVersion = request.GetRequestedApiVersion() ?? GetApiVersionFromRoutePrefix( request, route );
var requestedVersion = ResolveApiVersion( request, route );

if ( requestedVersion != null )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Web.Http.Dispatcher;
using Versioning;
using static Controllers.HttpControllerDescriptorComparer;
using static System.Net.HttpStatusCode;
using static System.StringComparer;

/// <summary>
Expand Down Expand Up @@ -68,6 +69,8 @@ public virtual HttpControllerDescriptor SelectController( HttpRequestMessage req
Arg.NotNull( request, nameof( request ) );
Contract.Ensures( Contract.Result<HttpControllerDescriptor>() != null );

EnsureRequestHasValidApiVersion( request );

var aggregator = new ApiVersionControllerAggregator( request, GetControllerName, controllerInfoCache );
var conventionRouteSelector = new ConventionRouteControllerSelector( options, controllerTypeCache );
var conventionRouteResult = default( ControllerSelectionResult );
Expand Down Expand Up @@ -119,10 +122,10 @@ public virtual string GetControllerName( HttpRequestMessage request )
return null;
}

string controller;
object controller;
routeData.Values.TryGetValue( RouteDataTokenKeys.Controller, out controller );

return controller;
return (string) controller;
}

private ConcurrentDictionary<string, HttpControllerDescriptorGroup> InitializeControllerInfoCache()
Expand Down Expand Up @@ -151,5 +154,20 @@ private ConcurrentDictionary<string, HttpControllerDescriptorGroup> InitializeCo

return mapping;
}

private static void EnsureRequestHasValidApiVersion( HttpRequestMessage request )
{
Contract.Requires( request != null );

try
{
var apiVersion = request.GetRequestedApiVersion();
}
catch ( AmbiguousApiVersionException ex )
{
var error = new HttpError( ex.Message ) { ["Code"] = "AmbiguousApiVersion" };
throw new HttpResponseException( request.CreateErrorResponse( BadRequest, error ) );
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@ private HttpResponseException CreateBadRequestForUnsupportedApiVersion( Controll

var message = SR.VersionedResourceNotSupported.FormatDefault( request.RequestUri, requestedVersion );
var messageDetail = SR.VersionedControllerNameNotFound.FormatDefault( request.RequestUri, requestedVersion );
var error = new HttpError() { Message = message, MessageDetail = messageDetail };

error["Code"] = "UnsupportedApiVersion";
traceWriter.Info( request, ControllerSelectorCategory, message );

return new HttpResponseException( request.CreateErrorResponse( BadRequest, message, messageDetail ) );
return new HttpResponseException( request.CreateErrorResponse( BadRequest, error ) );
}

[SuppressMessage( "Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Created exception cannot be disposed. Handled by the caller." )]
Expand All @@ -68,10 +70,12 @@ private HttpResponseException CreateBadRequestForInvalidApiVersion()

var message = SR.VersionedResourceNotSupported.FormatDefault( request.RequestUri, requestedVersion );
var messageDetail = SR.VersionedControllerNameNotFound.FormatDefault( request.RequestUri, requestedVersion );
var error = new HttpError() { Message = message, MessageDetail = messageDetail };

error["Code"] = "InvalidApiVersion";
traceWriter.Info( request, ControllerSelectorCategory, message );

return new HttpResponseException( request.CreateErrorResponse( BadRequest, message, messageDetail ) );
return new HttpResponseException( request.CreateErrorResponse( BadRequest, error ) );
}

[SuppressMessage( "Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Created exception cannot be disposed. Handled by the caller." )]
Expand Down
Loading