This commit is contained in:
陈向学 2024-06-13 14:13:22 +08:00
parent c5d2b808ee
commit a8c87587ab
25 changed files with 971 additions and 0 deletions

View File

@ -0,0 +1,5 @@
{
"version": 1,
"isRoot": true,
"tools": {}
}

View File

@ -0,0 +1,86 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<None Remove="Controllers\demo\p3k2d4gz.r22~" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="log4net" Version="2.0.15" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.28" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="8.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.22" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.35.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
<PackageReference Include="NPOI" Version="2.5.2" />
<PackageReference Include="Polly" Version="8.4.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.2.7" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Competition.Common\Competition.Common.csproj" />
<ProjectReference Include="..\Competition.Mysql\Competition.Mysql.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="CompetitionAPI.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Dockerfile">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="msyh.ttc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\Json\" />
</ItemGroup>
<ItemGroup>
<Content Update="wwwroot\Upload\1.jpg">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\3.mp4">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\excel.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\Excel\用户管理模板.xls">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\测试.doc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\测试excel.xls">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\测试ppt.ppt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\演示文稿.pptx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\编辑器功能.pdf">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Upload\职业道德.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>CompetitionAPI</ActiveDebugProfile>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
<NameOfLastUsedPublishProfile>F:\项目\禄口机场农电竞赛\web\LKJCpowerSupplyOfficeSimulationSystem\CompetitionAPI\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,3 @@
<?xml version="1.0"?>
<doc>
</doc>

View File

@ -0,0 +1,67 @@
using Competition.Common.Util;
using Microsoft.AspNetCore.Mvc;
using NPOI.POIFS.Crypt.Dsig;
using System;
namespace CompetitionAPI.Controllers.api
{
//企业接口
[Route("api/[controller]/[action]")]
[ApiController]
public class CorporationController : Controller
{
Competition.Mysql.BLL.T_BAS_CORPORATION bll = new Competition.Mysql.BLL.T_BAS_CORPORATION();
public IConfiguration Configuration { get; }
public CorporationController(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 企业
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpGet]
public JsonResult Index(string action,string name)
{
if (action == "getNum")
{
//获取监管企业总数接口
//读取配置文件示例
var mysql = Configuration.GetConnectionString("MySQL").ToString();
//查询企业表所有数据
var list = bll.GetModelList("");
//按海关区分组统计
int rongCheng = 0;
int maWei = 0;
int ningDe = 0;
int puTian = 0;
int sanMing = 0;
int pingTan = 0;
int changLeJiChang = 0;
int wuYiShan = 0;
list.ForEach(model =>
{
if (model.CUSTOMS_CODE == "3500" || model.CUSTOMS_CODE == "3505")
{
//蓉城
rongCheng++;
}
});
var data = new { rongCheng = rongCheng, maWei = maWei, ningDe = ningDe, puTian = puTian, sanMing = sanMing, pingTan = pingTan, changLeJiChang = changLeJiChang, wuYiShan = wuYiShan };
return Json(Tool.GetJsonWithCode(APICode.Success, data));
}
else
{
return Json(Tool.GetJsonWithCode(APICode.Fail, "参数输入错误"));
}
}
}
}

View File

@ -0,0 +1,37 @@
using Competition.Common.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CompetitionAPI.Controllers.api
{
[Route("api/[controller]")]
[ApiController]
public class TestController : Controller
{
Competition.Mysql.BLL.T_BAS_CORPORATION bll = new Competition.Mysql.BLL.T_BAS_CORPORATION();
public IConfiguration Configuration { get; }
public TestController(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 获取企业接口
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpGet]
public JsonResult Index()
{
//读取配置文件示例
var mysql = Configuration.GetConnectionString("MySQL").ToString();
//查询企业表所有数据
var list = bll.GetModelList("");
return Json(Tool.GetJsonWithCode(APICode.Success, list));
}
}
}

View File

@ -0,0 +1,28 @@
using Competition.Common.Util;
using Microsoft.AspNetCore.Mvc;
using NPOI.POIFS.Crypt.Dsig;
namespace CompetitionAPI.Controllers.api
{
//堆场接口
[Route("api/[controller]/[action]")]
[ApiController]
public class YardController : Controller
{
Competition.Mysql.BLL.T_BAS_YARD bll = new Competition.Mysql.BLL.T_BAS_YARD();
public IConfiguration Configuration { get; }
public YardController(IConfiguration configuration)
{
Configuration = configuration;
}
[HttpGet]
public JsonResult Index(string action, string name)
{
return Json(Tool.GetJsonWithCode(APICode.Success, null));
}
}
}

View File

@ -0,0 +1,63 @@
using Competition.Common.Util;
using CompetitionAPI.api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Reflection.Emit;
namespace CompetitionAPI.Controllers.unity
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : Controller
{
//private readonly TokenService _tokenService;
//private readonly IHttpContextAccessor _httpContextAccessor;
//public LoginController(IHttpContextAccessor httpContextAccessor, TokenService tokenService)
//{
// _httpContextAccessor = httpContextAccessor;
// _tokenService = tokenService;
//}
///// <summary>
///// 登录接口
///// </summary>
///// <param name="req"></param>
///// <returns></returns>
//[HttpPost]
//public JsonResult Index([FromBody] LoginRequest req)
//{
// try
// {
// if (!string.IsNullOrWhiteSpace(req.login_name) && !string.IsNullOrWhiteSpace(req.password))
// {
// var value = RSAHelper.DecryptData(req.password);
// var pwd = EncryptionAndDecryption.EncryptByLgzn(value);
// var models = bll.GetModelList(string.Format(" login_name = '{0}' ", req.login_name));
// if (models != null && models.Any() && models.First().password.Equals(pwd))
// {
// //登录成功
// var login_ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
// var model = models.First();
// string token = _tokenService.GenerateToken(model.user_id);
// return Json(Tool.GetJsonWithCode(APICode.Success, new { token = token, user_id = model.user_id, login_name = model.login_name, real_name = model.real_name, r3 = model.r3, role_id = model.role_id, dep_name = model.dep_name }));
// }
// else
// {
// return Json(Tool.GetJsonWithCode(APICode.Fail, "用户名或密码错误!"));
// }
// }
// else
// {
// return Json(Tool.GetJsonWithCode(APICode.Fail, "用户名或密码不能为空!"));
// }
// }
// catch (Exception ex)
// {
// return Json(Tool.GetJsonWithCode(APICode.Fail, ex.Message));
// }
//}
}
}

View File

@ -0,0 +1,123 @@
using Competition.Common.Util;
using CompetitionAPI.api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.POIFS.Crypt.Dsig;
using Polly;
namespace CompetitionAPI.Controllers.demo
{
[Route("api/[controller]")]
[ApiController]
public class UploadController : Controller
{
//private readonly IWebHostEnvironment _webHostEnvironment;
//public IConfiguration Configuration { get; }
//public UploadController(IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
//{
// _webHostEnvironment = webHostEnvironment;
// Configuration = configuration;
//}
///// <summary>
///// 分片上传文件接口
///// </summary>
///// <param name="file">请求参数</param>
///// <returns></returns>
//[Authorize]
//[HttpPost]
//public async Task<JsonResult> RuleUploadFile([FromQuery] SliceFileInfo file)
//{
// try
// {
// string path = Path.Combine(_webHostEnvironment.WebRootPath, "Upload", file.FolderName);
// var files = Request.Form.Files;
// var buffer = new byte[file.Size];
// var fileName = file.Name.Replace("(", "").Replace(")", "").Replace("", "").Replace("", "");
// path = path + "//" + fileName + "//";
// if (!Directory.Exists(path))
// {
// Directory.CreateDirectory(path);
// }
// string filepath = path + "//" + file.Name.Replace("(", "").Replace(")", "").Replace("", "").Replace("", "") + "^" + file.Number;
// using (var stream = new FileStream(filepath, FileMode.Append))
// {
// await files[0].CopyToAsync(stream);
// }
// var filesList = Directory.GetFiles(Path.GetDirectoryName(path));
// //当顺序号等于分片总数量 合并文件
// if (file.Number + 1 == file.Count || filesList.Length == file.Count)
// {
// await MergeFile(file);
// return Json(Tool.GetJsonWithCode(APICode.Success, "/Upload/" + file.FolderName + "/" + file.Name.Replace("(", "").Replace(")", "").Replace("", "").Replace("", "") + "/" + fileName.Split("~")[0].ToString()));
// }
// else
// {
// return Json(Tool.GetJsonWithCode(APICode.Success, "成功"));
// }
// }
// catch (Exception ex)
// {
// return Json(Tool.GetJsonWithCode(APICode.Fail, ex.Message));
// }
//}
///// <summary>
///// 合并文件
///// </summary>
///// <param name="file"></param>
///// <returns></returns>
//private async Task MergeFile(SliceFileInfo file)
//{
// string path = Path.Combine(_webHostEnvironment.WebRootPath, "Upload", file.FolderName);
// var fileName = file.Name.Replace("(", "").Replace(")", "").Replace("", "").Replace("", "");
// path = path + "//" + fileName + "//";
// string baseFileName = path + fileName.Split("~")[0].ToString();
// if (!Directory.Exists(path))
// {
// Directory.CreateDirectory(path);
// }
// var filesList = Directory.GetFiles(Path.GetDirectoryName(path));
// if (filesList.Length != file.Count)
// {
// return;
// }
// List<FileSort> lstFile = new List<FileSort>();
// foreach (var item in filesList)
// {
// lstFile.Add(new FileSort()
// {
// Name = item,
// NumBer = Convert.ToInt32(item.Substring(item.IndexOf('^') + 1))
// });
// }
// lstFile = lstFile.OrderBy(x => x.NumBer).ToList();
// using (var fileStream = new FileStream(baseFileName, FileMode.Create))
// {
// await Policy.Handle<IOException>()
// .RetryForeverAsync()
// .ExecuteAsync(async () =>
// {
// foreach (var fileSort in lstFile)
// {
// using (FileStream fileChunk = new FileStream(fileSort.Name, FileMode.Open))
// {
// await fileChunk.CopyToAsync(fileStream);
// }
// }
// });
// }
// //删除分片文件
// foreach (var dirfile in filesList)
// {
// System.IO.File.Delete(dirfile);
// }
//}
}
}

View File

@ -0,0 +1,55 @@
using Competition.Common.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CompetitionAPI.Controllers.demo
{
[Route("api/[controller]")]
[ApiController]
public class UploadFileController : Controller
{
//private readonly IWebHostEnvironment _webHostEnvironment;
//public UploadFileController(IWebHostEnvironment webHostEnvironment)
//{
// _webHostEnvironment = webHostEnvironment;
//}
///// <summary>
///// 上传文件接口
///// </summary>
///// <param name="req"></param>
///// <returns></returns>
//[Authorize]
//[HttpPost]
//public async Task<JsonResult> Index([FromForm] IFormFile Files)
//{
// try
// {
// if (Files.Length <= 0)
// {
// return Json(Tool.GetJsonWithCode(APICode.Fail, "文件不能为空"));
// }
// // Handle file upload
// var fileName = Guid.NewGuid().ToString() + Path.GetExtension(Files.FileName);
// var folderPath = "/Upload/PlayBack/";
// if (!Directory.Exists(_webHostEnvironment.WebRootPath + folderPath))
// {
// Directory.CreateDirectory(_webHostEnvironment.WebRootPath + folderPath);
// }
// var filePath = folderPath + fileName;
// var serverPath = _webHostEnvironment.WebRootPath + filePath;
// using (var stream = new FileStream(serverPath, FileMode.Create))
// {
// await Files.CopyToAsync(stream);
// }
// return Json(Tool.GetJsonWithCode(APICode.Success, filePath));
// }
// catch (Exception e)
// {
// return Json(Tool.GetJsonWithCode(APICode.Fail, e.Message));
// }
//}
}
}

View File

@ -0,0 +1,13 @@
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 5000
COPY ./ ./
RUN apt-get update && apt-get upgrade -y fontconfig && apt-get install -y fontconfig
COPY ./msyh.ttc /usr/share/fonts/
ENTRYPOINT ["dotnet", "CompetitionAPI.dll"]

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="SysAppender" />
</root>
<logger name="WebLogger">
<level value="DEBUG" />
</logger>
<appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="App_Data/" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
<param name="Header" value=" ------------------------------------------------&#xD;&#xA;" />
<param name="Footer" value=" ------------------------------------------------&#xD;&#xA;" />
</layout>
</appender>
<appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
</log4net>
</configuration>

View File

@ -0,0 +1,22 @@
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
namespace CompetitionAPI
{
public class Program
{
public static void Main(string[] args)
{
//log4net.Config.XmlConfigurator.Configure();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls("http://*:4000");
webBuilder.UseStartup<Startup>();
});
}
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net6.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net6.0</TargetFramework>
<ProjectGuid>282944fe-ebe1-43de-8a19-ac2227eb0b49</ProjectGuid>
<SelfContained>false</SelfContained>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<_PublishTargetUrl>F:\项目\禄口机场农电竞赛\web\LKJCpowerSupplyOfficeSimulationSystem\CompetitionAPI\bin\Release\net6.0\publish\</_PublishTargetUrl>
<History>True|2024-05-27T09:59:34.3727916Z;True|2024-05-27T17:27:21.4996385+08:00;True|2024-05-27T17:23:24.9444411+08:00;True|2024-05-27T16:43:46.9559439+08:00;True|2024-05-27T15:15:18.3136214+08:00;True|2024-05-27T14:57:33.2042444+08:00;True|2024-05-27T14:57:14.8310354+08:00;True|2024-05-27T11:33:28.6117998+08:00;True|2024-05-22T17:06:03.2185107+08:00;True|2024-05-22T16:51:11.5843931+08:00;True|2024-05-22T16:50:29.7077830+08:00;True|2024-05-22T09:09:27.6793247+08:00;True|2024-05-22T09:08:20.9885264+08:00;True|2024-05-21T16:28:25.1632625+08:00;True|2024-05-21T16:13:24.5762820+08:00;True|2024-05-21T16:11:22.8171949+08:00;True|2024-05-20T17:56:12.9722002+08:00;False|2024-05-20T17:54:46.9802518+08:00;True|2024-05-20T16:25:58.0026284+08:00;True|2024-05-20T10:57:43.6196683+08:00;True|2024-05-07T17:29:19.0977936+08:00;True|2024-04-25T14:46:11.0800146+08:00;True|2024-04-25T14:43:40.5999345+08:00;True|2024-04-25T14:32:31.3434782+08:00;True|2024-04-25T10:54:06.1748373+08:00;True|2024-04-24T08:34:12.3894499+08:00;True|2024-04-23T17:47:16.5593064+08:00;True|2024-04-23T09:28:02.9300433+08:00;True|2024-04-19T10:12:19.9178859+08:00;True|2024-04-19T10:10:34.7478867+08:00;False|2024-04-19T10:09:51.2148864+08:00;True|2024-04-18T16:40:44.1239202+08:00;True|2024-04-18T16:38:39.4769203+08:00;True|2024-04-16T12:52:22.4136113+08:00;True|2024-04-16T10:43:06.8211351+08:00;True|2024-04-15T08:54:00.5605696+08:00;False|2024-04-15T08:53:24.3458067+08:00;False|2024-04-15T08:52:59.4025282+08:00;True|2024-04-12T15:22:25.5880795+08:00;True|2024-04-12T15:13:53.6569483+08:00;True|2024-04-12T15:02:32.1135053+08:00;True|2024-04-12T14:35:24.1835608+08:00;True|2024-04-11T15:59:47.5218620+08:00;True|2024-04-11T15:53:18.1175657+08:00;True|2024-04-11T15:42:27.1647855+08:00;True|2024-04-11T15:20:56.5459552+08:00;True|2024-04-11T15:15:22.8015288+08:00;True|2024-04-11T14:39:19.6099392+08:00;True|2024-04-11T14:29:11.7341566+08:00;True|2024-04-11T14:20:25.8902473+08:00;True|2024-04-11T13:56:35.0704589+08:00;True|2024-04-11T13:55:12.9593229+08:00;True|2024-04-11T13:51:43.7707577+08:00;True|2024-04-11T13:40:51.3384101+08:00;True|2024-04-11T10:28:44.3846991+08:00;True|2024-04-11T10:10:42.2051862+08:00;True|2024-04-10T15:17:47.7949258+08:00;True|2024-04-10T13:31:58.0311656+08:00;True|2024-04-08T15:14:46.8401681+08:00;True|2024-04-08T15:06:27.9183399+08:00;True|2024-04-08T14:43:33.8042542+08:00;True|2024-04-08T14:19:00.0294174+08:00;True|2024-04-08T14:16:39.0769849+08:00;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>

View File

@ -0,0 +1,37 @@
{
"profiles": {
"CompetitionAPI": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:4000"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"publishAllPorts": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:17785",
"sslPort": 0
}
}
}

View File

@ -0,0 +1,180 @@
using Autofac;
using log4net;
using log4net.Config;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.OpenApi.Models;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using System.Linq;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Autofac.Core;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Newtonsoft.Json;
using Competition.Common.Util;
using static System.Net.WebRequestMethods;
namespace CompetitionAPI
{
public class Startup
{
public static log4net.Repository.ILoggerRepository repository;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
repository = LogManager.CreateRepository("NETCoreRepository");
XmlConfigurator.Configure(repository, new FileInfo("Log4net.config"));
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//配置跨域访问问题
services.AddCors(
options => options.AddPolicy("CorsTest",
p => p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
)
);
services.Configure<FormOptions>(options =>
{
options.KeyLengthLimit = int.MaxValue;
options.ValueLengthLimit = int.MaxValue;
options.MultipartBodyLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = int.MaxValue;
options.Limits.MaxRequestBufferSize = int.MaxValue;
});
//禁用自动模型验证
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
});
//注册Swagger生成器定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CompetitionAPI" });
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "CompetitionAPI.xml");
c.IncludeXmlComments(xmlPath);
});
services.AddControllers().AddNewtonsoftJson(options =>
{
//配置返回Json大小写格式与Model一致
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
//添加MVC组件
services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
});
//注入Http
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//// 确保 TokenService 类被正确注册
//services.AddSingleton<TokenService>(new TokenService(Configuration["Jwt:SecretKey"], Configuration["Jwt:Issuer"]));
//// 添加身份验证服务
//services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// .AddJwtBearer(options =>
// {
// options.TokenValidationParameters = new TokenValidationParameters
// {
// ValidateIssuer = true,
// ValidIssuer = Configuration["Jwt:Issuer"],
// ValidateIssuerSigningKey = true,
// IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
// ValidateAudience = false,
// ValidateLifetime = true,
// ClockSkew = TimeSpan.Zero
// };
// options.Events = new JwtBearerEvents
// {
// //此处为权限验证失败后触发的事件
// OnChallenge = context =>
// {
// //此处代码为终止.Net Core默认的返回类型和数据结果这个很重要哦必须
// context.HandleResponse();
// var response = Tool.GetJsonWithCode(APICode.Fail, "Authentication failed");
// //自定义自己想要返回的数据结果我这里要返回的是Json对象通过引用Newtonsoft.Json库进行转换
// var payload = JsonConvert.SerializeObject(response);
// //自定义返回的数据类型
// context.Response.ContentType = "application/json";
// //自定义返回状态码默认为401 我这里改成 200
// context.Response.StatusCode = StatusCodes.Status401Unauthorized;
// //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
// //输出Json数据结果
// context.Response.WriteAsync(payload);
// return Task.FromResult(0);
// }
// };
// });
}
public void ConfigureContainer(ContainerBuilder builder)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
//defaultFilesOptions.DefaultFileNames.Clear();
//defaultFilesOptions.DefaultFileNames.Add("index.html");
//app.UseDefaultFiles(defaultFilesOptions);
app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true });
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// 启用身份验证中间件
app.UseAuthentication();
app.UseRouting();
app.UseCors("CorsTest");//其中app.UseCors()必须放在app.UseRouting()和app.UseEndpoints之间不然还是解决不了问题。
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CompetitionAPI");
});
}
}
}

View File

@ -0,0 +1,39 @@
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using CompetitionAPI.api;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace CompetitionAPI
{
public class TokenService
{
private readonly string _secretKey;
private readonly string _issuer;
public TokenService(string secretKey, string issuer)
{
_secretKey = secretKey;
_issuer = issuer;
}
public string GenerateToken(string userId)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_secretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("userId", userId) }),
Expires = DateTime.UtcNow.AddHours(3), // Token 过期时间
Issuer = _issuer,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
//注意:使用高版本下面这行代码会报错
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
}
}

View File

@ -0,0 +1,46 @@
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Security.Claims;
namespace CompetitionAPI
{
public class TokenValidationService
{
private readonly string _secretKey;
private readonly string _issuer;
public TokenValidationService(string secretKey, string issuer)
{
_secretKey = secretKey;
_issuer = issuer;
}
public bool ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_secretKey);
try
{
tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = _issuer,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateAudience = false, // 可选:是否验证 Audience
ValidateLifetime = true, // 是否验证 Token 是否过期
ClockSkew = TimeSpan.Zero // 设置时间偏差
}, out var validatedToken);
return validatedToken != null;
}
catch (Exception)
{
// Token 验证失败
return false;
}
}
}
}

View File

@ -0,0 +1,15 @@
using log4net;
namespace CompetitionAPI.Util
{
public class LogHelper
{
private static readonly ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(LogHelper));
//private static readonly log4net.ILog logger = log4net.LogManager.GetLogger("LogHelper");
public static void WriteLog(string msg)
{
log.Info(msg);
}
}
}

View File

@ -0,0 +1,14 @@
namespace CompetitionAPI.api
{
public class FileSort
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 序号
/// </summary>
public int NumBer { get; set; }
}
}

View File

@ -0,0 +1,39 @@
namespace CompetitionAPI.api
{
public class SliceFileInfo
{
/// <summary>
/// 文件名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 编号
/// </summary>
public int Number { get; set; }
/// <summary>
/// 分片大小
/// </summary>
public int BufferSize { get; set; }
/// <summary>
/// 分片总数
/// </summary>
public int Count { get; set; }
/// <summary>
/// 文件开始位置
/// </summary>
public int Start { get; set; }
/// <summary>
/// 文件结束位置
/// </summary>
public int End { get; set; }
/// <summary>
/// 文件总大小
/// </summary>
public int Size { get; set; }
/// <summary>
/// 文件夹名称
/// </summary>
public string FolderName { get; set; }
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"MySQL": "server=172.16.1.162;uid=sa;pwd=p@ssw0rd;database=SHJGEnt_HNHG;"
},
"AllowedHosts": "*"
}

Binary file not shown.