Skip to content

Commit a0950f7

Browse files
author
Bart Koelman
committed
Fixed: only run custom path cutting logic when RouteAttribute is used
1 parent c079e0d commit a0950f7

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs

+15-7
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using JsonApiDotNetCore.Managers.Contracts;
1313
using JsonApiDotNetCore.Models.JsonApiDocuments;
1414
using Microsoft.AspNetCore.Http;
15+
using Microsoft.AspNetCore.Mvc;
1516
using Microsoft.AspNetCore.Routing;
1617
using Microsoft.Extensions.Primitives;
1718
using Newtonsoft.Json;
@@ -181,7 +182,7 @@ private static string GetBasePath(string resourceName, IJsonApiOptions options,
181182
builder.Append(httpRequest.Host);
182183
}
183184

184-
string customRoute = GetCustomRoute(httpRequest.Path.Value, resourceName, options.Namespace);
185+
string customRoute = GetCustomRoute(resourceName, options.Namespace, httpRequest.HttpContext);
185186
if (!string.IsNullOrEmpty(customRoute))
186187
{
187188
builder.Append('/');
@@ -196,13 +197,20 @@ private static string GetBasePath(string resourceName, IJsonApiOptions options,
196197
return builder.ToString();
197198
}
198199

199-
private static string GetCustomRoute(string path, string resourceName, string apiNamespace)
200+
private static string GetCustomRoute(string resourceName, string apiNamespace, HttpContext httpContext)
200201
{
201-
var trimmedComponents = path.Trim('/').Split('/').ToList();
202-
var resourceNameIndex = trimmedComponents.FindIndex(c => c == resourceName);
203-
var newComponents = trimmedComponents.Take(resourceNameIndex).ToArray();
204-
var customRoute = string.Join('/', newComponents);
205-
return customRoute == apiNamespace ? null : customRoute;
202+
var endpoint = httpContext.GetEndpoint();
203+
var routeAttribute = endpoint.Metadata.GetMetadata<RouteAttribute>();
204+
if (routeAttribute != null)
205+
{
206+
var trimmedComponents = httpContext.Request.Path.Value.Trim('/').Split('/').ToList();
207+
var resourceNameIndex = trimmedComponents.FindIndex(c => c == resourceName);
208+
var newComponents = trimmedComponents.Take(resourceNameIndex).ToArray();
209+
var customRoute = string.Join('/', newComponents);
210+
return customRoute == apiNamespace ? null : customRoute;
211+
}
212+
213+
return null;
206214
}
207215

208216
private static bool GetIsRelationshipPath(RouteValueDictionary routeValues)

test/UnitTests/Middleware/JsonApiMiddlewareTests.cs

+1
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ private static DefaultHttpContext CreateHttpContext(string path, bool isRelation
144144
feature.RouteValues["id"] = id;
145145
}
146146
context.Features.Set<IRouteValuesFeature>(feature);
147+
context.SetEndpoint(new Endpoint(null, new EndpointMetadataCollection(), null));
147148
return context;
148149
}
149150

0 commit comments

Comments
 (0)