WebApi Changes

This commit is contained in:
Brett Hewitson 2023-03-07 20:40:37 +10:00
parent d217c08ab0
commit 33af7cf391
17 changed files with 319 additions and 309 deletions

View file

@ -1,27 +0,0 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ServerManager.WebApplication.Controllers;
[Route("api/[controller]")]
[ApiController]
[ApiVersion("1.0")]
[Produces("application/json")]
public class HealthController : ControllerBase
{
[HttpGet()]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Get()
{
try
{
return Ok();
}
catch
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}

View file

@ -1,12 +1,10 @@
using Microsoft.AspNetCore.Http; using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServerManager.WebApplication.Models; using ServerManager.WebApplication.Models;
using ServerManager.WebApplication.Models.ApiVersion1; using ServerManager.WebApplication.Models.ApiVersion1;
using ServerManager.WebApplication.Services; using ServerManager.WebApplication.Services;
using System;
using System.Collections.Generic;
namespace ServerManager.WebApplication.Controllers; namespace ServerManager.WebApplication.Controllers;

View file

@ -0,0 +1,18 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ServerManager.WebApplication.Models.Data;
using ServerManager.WebApplication.Services;
namespace ServerManager.WebApplication.Extensions;
public static class ServerQueryExtensions
{
public static IServiceCollection AddServerQueryServices(this IServiceCollection services, IConfiguration configuration)
{
var settings = configuration.GetSectionAs<ServerQuerySettings>();
services.AddSingleton(settings);
services.AddScoped<IServerQueryService, QueryMasterService>();
return services;
}
}

View file

@ -0,0 +1,14 @@
using Microsoft.Extensions.Configuration;
namespace ServerManager.WebApplication.Extensions;
public static class ServiceCollectionExtensions
{
public static T GetSectionAs<T>(this IConfiguration configuration, string sectionName = null)
{
if (string.IsNullOrWhiteSpace(sectionName))
sectionName = typeof(T).Name;
return configuration.GetSection(sectionName).Get<T>();
}
}

View file

@ -1,56 +0,0 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
using System.Text.Json;
namespace ServerManager.WebApplication.Extensions
{
public class SwaggerDefaultValues : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var apiDescription = context.ApiDescription;
operation.Deprecated |= apiDescription.IsDeprecated();
foreach (var responseType in context.ApiDescription.SupportedResponseTypes)
{
var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString();
var response = operation.Responses[responseKey];
foreach (var contentType in response.Content.Keys)
{
if (!responseType.ApiResponseFormats.Any(x => x.MediaType == contentType))
{
response.Content.Remove(contentType);
}
}
}
if (operation.Parameters is null)
{
return;
}
foreach (var parameter in operation.Parameters)
{
var description = apiDescription.ParameterDescriptions
.First(p => p.Name == parameter.Name);
if (parameter.Description is null)
{
parameter.Description = description.ModelMetadata?.Description;
}
if (parameter.Schema.Default is null && description.DefaultValue is not null)
{
var json = JsonSerializer.Serialize(description.DefaultValue, description.ModelMetadata.ModelType);
parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson(json);
}
parameter.Required |= description.IsRequired;
}
}
}
}

View file

@ -0,0 +1,55 @@
using System.Linq;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace ServerManager.WebApplication.Middleware;
public class SwaggerDefaultValues : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var apiDescription = context.ApiDescription;
operation.Deprecated |= apiDescription.IsDeprecated();
foreach (var responseType in context.ApiDescription.SupportedResponseTypes)
{
var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString();
var response = operation.Responses[responseKey];
foreach (var contentType in response.Content.Keys)
{
if (!responseType.ApiResponseFormats.Any(x => x.MediaType == contentType))
{
response.Content.Remove(contentType);
}
}
}
if (operation.Parameters is null)
{
return;
}
foreach (var parameter in operation.Parameters)
{
var description = apiDescription.ParameterDescriptions
.First(p => p.Name == parameter.Name);
if (parameter.Description is null)
{
parameter.Description = description.ModelMetadata?.Description;
}
if (parameter.Schema.Default is null && description.DefaultValue is not null)
{
var json = JsonSerializer.Serialize(description.DefaultValue, description.ModelMetadata.ModelType);
parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson(json);
}
parameter.Required |= description.IsRequired;
}
}
}

View file

@ -2,8 +2,8 @@
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace ServerManager.WebApplication.Models.ApiVersion1 namespace ServerManager.WebApplication.Models.ApiVersion1;
{
public class ErrorResponse public class ErrorResponse
{ {
/// <summary> /// <summary>
@ -13,4 +13,3 @@ namespace ServerManager.WebApplication.Models.ApiVersion1
[Description("List of errors.")] [Description("List of errors.")]
public ICollection<string> Errors { get; set; } = new List<string>(); public ICollection<string> Errors { get; set; } = new List<string>();
} }
}

View file

@ -1,8 +1,8 @@
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace ServerManager.WebApplication.Models.ApiVersion1 namespace ServerManager.WebApplication.Models.ApiVersion1;
{
public class ServerStatusResponse public class ServerStatusResponse
{ {
/// <summary> /// <summary>
@ -12,4 +12,3 @@ namespace ServerManager.WebApplication.Models.ApiVersion1
[Description("True if the server is available; otherwise false.")] [Description("True if the server is available; otherwise false.")]
public string Available { get; set; } = false.ToString(); public string Available { get; set; } = false.ToString();
} }
}

View file

@ -1,7 +1,7 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace ServerManager.WebApplication.Models.Data namespace ServerManager.WebApplication.Models.Data;
{
[DataContract] [DataContract]
public class ManagerCode public class ManagerCode
{ {
@ -10,4 +10,3 @@ namespace ServerManager.WebApplication.Models.Data
[DataMember] [DataMember]
public string Code { get; set; } = string.Empty; public string Code { get; set; } = string.Empty;
} }
}

View file

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace ServerManager.WebApplication.Models.Data
{
public class ServerQuerySettings
{
public List<ManagerCode> ManagerCodes { get; set; }
}
}

View file

@ -2,8 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace ServerManager.WebApplication.Models namespace ServerManager.WebApplication.Models;
{
public class ServerManagerApiException : Exception public class ServerManagerApiException : Exception
{ {
public ServerManagerApiException() : base() public ServerManagerApiException() : base()
@ -28,4 +28,3 @@ namespace ServerManager.WebApplication.Models
public ICollection<string> Messages { get; private set; } = new List<string>(); public ICollection<string> Messages { get; private set; } = new List<string>();
} }
}

View file

@ -1,8 +1,8 @@
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
namespace ServerManager.WebApplication namespace ServerManager.WebApplication;
{
public class Program public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
@ -17,4 +17,3 @@ namespace ServerManager.WebApplication
webBuilder.UseStartup<Startup>(); webBuilder.UseStartup<Startup>();
}); });
} }
}

View file

@ -1,7 +1,6 @@
namespace ServerManager.WebApplication.Services namespace ServerManager.WebApplication.Services;
{
public interface IServerQueryService public interface IServerQueryService
{ {
bool CheckServerStatus(string managerCode, string managerVersion, string ipString, int port); bool CheckServerStatus(string managerCode, string managerVersion, string ipString, int port);
} }
}

View file

@ -1,24 +1,21 @@
using Microsoft.AspNetCore.Http; using System;
using Microsoft.Extensions.Configuration;
using QueryMaster;
using ServerManager.WebApplication.Models;
using ServerManager.WebApplication.Models.Data;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using Microsoft.AspNetCore.Http;
using QueryMaster;
using ServerManager.WebApplication.Models;
using ServerManager.WebApplication.Models.Data;
namespace ServerManager.WebApplication.Services;
namespace ServerManager.WebApplication.Services
{
public class QueryMasterService : IServerQueryService public class QueryMasterService : IServerQueryService
{ {
internal const string CONFIG_MANAGERCODES = "ManagerCodes"; private readonly ServerQuerySettings _settings;
private readonly IConfiguration _configuration; public QueryMasterService(ServerQuerySettings settings)
public QueryMasterService(IConfiguration configuration)
{ {
_configuration = configuration; _settings = settings;
} }
public bool CheckServerStatus(string managerCode, string managerVersion, string ipString, int port) public bool CheckServerStatus(string managerCode, string managerVersion, string ipString, int port)
@ -28,9 +25,7 @@ namespace ServerManager.WebApplication.Services
try try
{ {
using var server = ServerQuery.GetServerInstance(EngineType.Source, ipString, (ushort)port); using var server = ServerQuery.GetServerInstance(EngineType.Source, ipString, (ushort)port);
return server.GetInfo() != null;
var serverInfo = server.GetInfo();
return serverInfo != null;
} }
catch catch
{ {
@ -48,7 +43,7 @@ namespace ServerManager.WebApplication.Services
} }
else else
{ {
var managerCodes = _configuration.GetSection(CONFIG_MANAGERCODES).Get<List<ManagerCode>>() ?? new List<ManagerCode>(); var managerCodes = _settings.ManagerCodes ?? new List<ManagerCode>();
if (!managerCodes.Any(c => c.Code.Equals(managerCode, StringComparison.OrdinalIgnoreCase))) if (!managerCodes.Any(c => c.Code.Equals(managerCode, StringComparison.OrdinalIgnoreCase)))
{ {
errors.Add("Manager code is invalid."); errors.Add("Manager code is invalid.");
@ -75,4 +70,3 @@ namespace ServerManager.WebApplication.Services
} }
} }
} }
}

View file

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.ApiExplorer;
@ -7,10 +8,10 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using ServerManager.WebApplication.Extensions; using ServerManager.WebApplication.Extensions;
using ServerManager.WebApplication.Services; using ServerManager.WebApplication.Middleware;
namespace ServerManager.WebApplication;
namespace ServerManager.WebApplication
{
public class Startup public class Startup
{ {
public Startup(IConfiguration configuration) public Startup(IConfiguration configuration)
@ -48,12 +49,14 @@ namespace ServerManager.WebApplication
o.GroupNameFormat = "'v'VVV"; o.GroupNameFormat = "'v'VVV";
}); });
services.AddScoped<IServerQueryService, QueryMasterService>(); services.AddServerQueryServices(Configuration);
services.AddSwaggerGen(o => services.AddSwaggerGen(o =>
{ {
o.OperationFilter<SwaggerDefaultValues>(); o.OperationFilter<SwaggerDefaultValues>();
}); });
services.AddHealthChecks();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -64,6 +67,7 @@ namespace ServerManager.WebApplication
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
} }
var enableSwagger = Configuration.GetValue<bool>("EnableSwagger"); var enableSwagger = Configuration.GetValue<bool>("EnableSwagger");
if (enableSwagger) if (enableSwagger)
{ {
@ -95,7 +99,10 @@ namespace ServerManager.WebApplication
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapControllers(); endpoints.MapControllers();
endpoints.MapHealthChecks("/api/health", new HealthCheckOptions()
{
AllowCachingResponses = false
});
}); });
} }
} }
}

View file

@ -7,9 +7,10 @@
} }
}, },
"EnableSwagger": false, "EnableSwagger": true,
"SwaggerRoutePrefix": "", "SwaggerRoutePrefix": "",
"ServerQuerySettings": {
"ManagerCodes": [ "ManagerCodes": [
{ {
"Name": "Unknown", "Name": "Unknown",
@ -17,3 +18,4 @@
} }
] ]
} }
}

View file

@ -2,6 +2,7 @@
"EnableSwagger": false, "EnableSwagger": false,
"SwaggerRoutePrefix": "", "SwaggerRoutePrefix": "",
"ServerQuerySettings": {
"ManagerCodes": [ "ManagerCodes": [
{ {
"Name": "Unknown", "Name": "Unknown",
@ -17,3 +18,4 @@
} }
] ]
} }
}