using Apimanager_backend.Dtos; using Apimanager_backend.Exceptions; using Apimanager_backend.Services; using Apimanager_backend.Tools; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Public; using System.Text.Json; namespace Apimanager_backend.Controllers { [Route("api/[controller]/{code}")] [ApiController] public class PublicController : ControllerBase { private BillableApiDispatcher _dispatcher; private IApiService _apiService; private IWebHostEnvironment _webHostEnvironment; public PublicController(BillableApiDispatcher billableApiDispatcher,IApiService apiService,IWebHostEnvironment webHostEnvironment) { _dispatcher = billableApiDispatcher; _apiService = apiService; _webHostEnvironment = webHostEnvironment; } [HttpGet,HttpDelete,HttpPost,HttpPut] [EnableRateLimiting("DynamicPerUser")] public async Task Invoke(string code) { var requestMethod = HttpContext.Request.Method; // GET, POST, etc. var api = await _apiService.GetApiInfoByEndpointAsync(code); if (api == null || !api.IsActive) throw new BaseException(3002,"接口不存在"); if (!string.Equals(api.Method.ToString(),requestMethod, StringComparison.OrdinalIgnoreCase)) throw new BaseException(3002,$"接口不支持{requestMethod}方法"); Dictionary parameters = new Dictionary(); // 获取参数 if ((requestMethod == "GET" && Request.Query.Count == 0) || (requestMethod == "POST" && Request.ContentLength == 0)) { parameters = new Dictionary(); } else { parameters = requestMethod switch { "GET" => HttpContext.Request.Query.ToDictionary(x => x.Key, x => (object)x.Value.ToString()), _ => await JsonSerializer.DeserializeAsync>(Request.Body) }; } //var userId = int.Parse(User.Claims.First(x => x.Type == "userId").Value); var context = new ApiCallContext { UserId = -1, HttpContext = HttpContext, Parameters = parameters }; var result = await _dispatcher.DispatchAsync(_webHostEnvironment.ContentRootPath,api.Id,api.Endpoint, context); return Ok(result); } } }