You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/IoT/IoT.Shared/Controllers/BaseDeviceController.cs

81 lines
2.8 KiB

using Application.Models;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace IoT.Shared.Controllers
{
public class BaseDeviceController : Controller
{
internal readonly IServiceProvider applicationService;
public BaseDeviceController(IServiceProvider applicationServices)
{
this.applicationService = applicationServices;
}
[ApiExplorerSettings(IgnoreApi = true)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")]
public string GetApiJson()
{
try
{
var prefix = $"/{RouteData.Values["controller"]}/";
using var scope = this.applicationService.CreateScope();
var serviceProvider = scope.ServiceProvider;
var cfg = serviceProvider.GetService<IConfiguration>();
var port = cfg["server.urls"].Split(':')[2];
var url = $"http://localhost:{port}/swagger/v1/swagger.json";
var hc = serviceProvider.GetService<IHttpClientFactory>().CreateClient();
var result = hc.GetStringAsync(url).Result;
var json = JsonConvert.DeserializeObject(result) as JObject;
var paths = json.Properties().FirstOrDefault(o => o.Name == "paths").Value as JObject;
var names = paths.Properties().Select(o => o.Name).ToList();
foreach (var item in names)
{
if (!item.StartsWith(prefix))
{
paths.Remove(item);
}
}
var realResult = JsonConvert.SerializeObject(json);
return realResult;
}
catch (Exception ex)
{
ex.PrintStack();
return null;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")]
public ApiResponse AsyncAction(Action action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
try
{
Task.Run(() =>
{
action();
});
}
catch (Exception ex)
{
ex.PrintStack();
return ApiResponse.Error(ex.GetMessage());
}
return ApiResponse.AsyncSuccess();
}
}
}