Skip to content

Global route prefix middleware #127

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 26 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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 PxWeb/Config/Api2/PxApiConfigurationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class PxApiConfigurationOptions
public int CacheTime { get; set; } = 5;
public int PageSize { get; set; }
public string BaseURL { get; set; } = String.Empty;
public string RoutePrefix { get; set; } = String.Empty;
public List<string> OutputFormats { get; set; } = new List<string>();
public string DefaultOutputFormat { get; set; } = String.Empty;

Expand Down
2 changes: 1 addition & 1 deletion PxWeb/Controllers/Api2/Admin/CacheController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public CacheController(IPxCache pxCache)
}

[HttpDelete]
[Route("/api/v2/admin/cache")]
[Route("/admin/cache")]
public IActionResult Clear()
{
_pxCache.Clear();
Expand Down
4 changes: 2 additions & 2 deletions PxWeb/Controllers/Api2/Admin/DatabaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public DatabaseController(IControllerStateProvider stateProvider, BackgroundWork
}

[HttpPut]
[Route("/api/v2/admin/database")]
[Route("/admin/database")]
[SwaggerOperation("Database")]
[SwaggerResponse(statusCode: 202, description: "Accepted")]
[SwaggerResponse(statusCode: 401, description: "Unauthorized")]
Expand Down Expand Up @@ -109,7 +109,7 @@ internal async Task createMenuXml(bool? langDependent, string? sortOrder, Cancel
}

[HttpGet]
[Route("/api/v2/admin/database")]
[Route("/admin/database")]
[SwaggerOperation("Database")]
[SwaggerResponse(statusCode: 200, description: "Success")]
[SwaggerResponse(statusCode: 401, description: "Unauthorized")]
Expand Down
6 changes: 3 additions & 3 deletions PxWeb/Controllers/Api2/Admin/SearchindexController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public SearchindexController(BackgroundWorkerQueue backgroundWorkerQueue, IContr
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("/api/v2/admin/searchindex")]
[Route("/admin/searchindex")]
[SwaggerOperation("IndexDatabase")]
[SwaggerResponse(statusCode: 202, description: "Accepted")]
[SwaggerResponse(statusCode: 401, description: "Unauthorized")]
Expand Down Expand Up @@ -84,7 +84,7 @@ public IActionResult IndexDatabase()
/// <param name="tables"></param>
/// <returns></returns>
[HttpPatch]
[Route("/api/v2/admin/searchindex")]
[Route("/admin/searchindex")]
[SwaggerOperation("IndexDatabase")]
[SwaggerResponse(statusCode: 202, description: "Accepted")]
[SwaggerResponse(statusCode: 401, description: "Unauthorized")]
Expand Down Expand Up @@ -135,7 +135,7 @@ public IActionResult IndexDatabase([FromBody, Required] string[] tables)
}

[HttpGet]
[Route("/api/v2/admin/searchindex")]
[Route("/admin/searchindex")]
[SwaggerOperation("IndexDatabase")]
[SwaggerResponse(statusCode: 200, description: "Success")]
[SwaggerResponse(statusCode: 401, description: "Unauthorized")]
Expand Down
4 changes: 2 additions & 2 deletions PxWeb/Controllers/Api2/NavigationApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public NavigationApiController(IDataSource dataSource, ILanguageHelper languageH
/// <summary>
/// Gets navigation item with the given id.
/// HttpGet
/// Route /api/v2/navigation/{id}
/// Route /navigation/{id}
/// </summary>
/// <param name="id">Id</param>
/// <param name="lang">The language if the default is not what you want.</param>
Expand All @@ -61,7 +61,7 @@ public override IActionResult GetNavigationById([FromRoute(Name = "id"), Require
/// <summary>
/// Browse the database structure
/// HttpGet
/// Route /api/v2/navigation
/// Route /navigation
/// </summary>
/// <param name="lang">The language if the default is not what you want.</param>
/// <response code="200">Success</response>
Expand Down
2 changes: 2 additions & 0 deletions PxWeb/Mappers/LinkCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ private string CreateURL(string endpointUrl, string language, bool showLangParam
StringBuilder sb = new StringBuilder();

sb.Append(_urlBase);
sb.Append("/");
sb.Append(endpointUrl);

if (showLangParam)
Expand All @@ -114,6 +115,7 @@ private string CreatePageURL(string endpointUrl, string language, bool showLangP
StringBuilder sb = new StringBuilder();

sb.Append(_urlBase);
sb.Append("/");
sb.Append(endpointUrl);

if (!string.IsNullOrEmpty(query) && showLangParam)
Expand Down
25 changes: 25 additions & 0 deletions PxWeb/Middleware/GlobalRoutePrefixMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

namespace PxWeb.Middleware
{

public class GlobalRoutePrefixMiddleware
{
private readonly RequestDelegate _next;
private readonly string _routePrefix;

public GlobalRoutePrefixMiddleware(RequestDelegate next, string routePrefix)
{
_next = next;
_routePrefix = routePrefix;
}

public async Task InvokeAsync(HttpContext context)
{
context.Request.PathBase = new PathString(_routePrefix);
await _next(context);
}
}
}
21 changes: 18 additions & 3 deletions PxWeb/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
using log4net;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;

using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
Expand Down Expand Up @@ -129,19 +131,32 @@ public static void Main(string[] args)
{
// Sort endpoints
c.OrderActionsBy((apiDesc) => $"{apiDesc.ActionDescriptor.RouteValues["controller"]}_{apiDesc.RelativePath}");
c.SwaggerDoc("v2", new OpenApiInfo
{
Title = "PxWebApi",
Version = "v2-beta"
}
);
});


// Handle CORS configuration from appsettings.json
bool corsEnbled = builder.Services.ConfigurePxCORS(builder, _logger);

var app = builder.Build();
var routePrefix = builder.Configuration.GetSection("PxApiConfiguration:RoutePrefix").Value;

app.UseMiddleware<GlobalRoutePrefixMiddleware>(routePrefix);
app.UsePathBase(new PathString(routePrefix));

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v2/swagger.json", "PxWebApi 2.0-beta");
});
}

app.UseHttpsRedirection();
Expand All @@ -156,7 +171,7 @@ public static void Main(string[] args)
{
app.UseAuthorization();

app.UseWhen(context => context.Request.Path.StartsWithSegments("/api/v2/admin"), appBuilder =>
app.UseWhen(context => context.Request.Path.StartsWithSegments(routePrefix + "/admin") || context.Request.Path.StartsWithSegments("/admin"), appBuilder =>
{
appBuilder.UseAdminProtectionIpWhitelist();
appBuilder.UseAdminProtectionKey();
Expand All @@ -169,7 +184,7 @@ public static void Main(string[] args)
app.UseIpRateLimiting();
}

app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api/v2/admin"), appBuilder =>
app.UseWhen(context => !context.Request.Path.StartsWithSegments(routePrefix + "/admin") || context.Request.Path.StartsWithSegments("/admin"), appBuilder =>
{
appBuilder.UseCacheMiddleware();
});
Expand Down
2 changes: 1 addition & 1 deletion PxWeb/PxWeb.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<PackageReference Include="PCAxis.Menu.ConfigDatamodelMenu" Version="1.0.8" />
<PackageReference Include="PCAxis.Serializers" Version="1.3.0" />
<PackageReference Include="PcAxis.Sql" Version="1.2.4" />
<PackageReference Include="PxWeb.Api2.Server" Version="0.0.2-alpha.0.38" />
<PackageReference Include="PxWeb.Api2.Server" Version="0.0.2-alpha.0.44" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.6.2" />
Expand Down
3 changes: 2 additions & 1 deletion PxWeb/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
"CacheTime": 86400,
"SearchEngine": "Lucene",
"PageSize": 20,
"BaseURL": "https://www.pxapi.com/api/v2/",
"BaseURL": "https://www.pxapi.com/api/v2",
"RoutePrefix": "/api/v2",
"OutputFormats": [
"xlsx",
"xlsx_doublecolumn",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
"CacheTime": 86400,
"SearchEngine": "Lucene",
"PageSize": 20,
"BaseURL": "https://www.pxapi.com/api/v2/",
"BaseURL": "https://www.pxapi.com/api/v2",
"RoutePrefix": "/api/v2",
"OutputFormats": [
"xlsx",
"xlsx_doublecolumn",
Expand Down
3 changes: 2 additions & 1 deletion PxWebApi.BigTests/ConfigController/test_appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"CacheTime": 86400,
"SearchEngine": "Lucene",
"PageSize": 20,
"BaseURL": "https://www.pxapi.com/api/v2/",
"BaseURL": "https://www.pxapi.com/api/v2",
"RoutePrefix": "/api/v2",
"OutputFormats": [
"xlsx",
"xlsx_doublecolumn",
Expand Down
3 changes: 2 additions & 1 deletion PxWebApi.BigTests/TableController/test_appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"CacheTime": 86400,
"SearchEngine": "Lucene",
"PageSize": 20,
"BaseURL": "https://www.pxapi.com/api/v2/",
"BaseURL": "https://www.pxapi.com/api/v2",
"RoutePrefix": "/api/v2",
"OutputFormats": [
"xlsx",
"xlsx_doublecolumn",
Expand Down