v2.0.0
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Autofac" Version="6.1.0" />
|
||||
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.5" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.4">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
@@ -15,8 +18,34 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CC.Yi.BLL\CC.Yi.BLL.csproj" />
|
||||
<ProjectReference Include="..\CC.Yi.Common\CC.Yi.Common.csproj" />
|
||||
<ProjectReference Include="..\CC.Yi.DAL\CC.Yi.DAL.csproj" />
|
||||
<ProjectReference Include="..\CC.Yi.IBLL\CC.Yi.IBLL.csproj" />
|
||||
<ProjectReference Include="..\CC.Yi.Model\CC.Yi.Model.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="T4Startup.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>T4Startup.tt</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="T4Startup.tt">
|
||||
<Generator>TextTemplatingFileGenerator</Generator>
|
||||
<LastGenOutput>T4Startup.cs</LastGenOutput>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
using CC.Yi.IBLL;
|
||||
using CC.Yi.Common;
|
||||
using CC.Yi.Common.Cache;
|
||||
using CC.Yi.Common.Jwt;
|
||||
using CC.Yi.IBLL;
|
||||
using CC.Yi.Model;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using ServiceStack.Redis;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CC.Yi.API.Controllers
|
||||
@@ -12,19 +25,138 @@ namespace CC.Yi.API.Controllers
|
||||
[Route("[controller]/[action]")]
|
||||
public class StudentController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<StudentController> _logger;
|
||||
private readonly ILogger<StudentController> _logger;//处理日志相关文件
|
||||
|
||||
//private UserManager<result_user> _userManager;//处理用户相关逻辑:添加密码,修改密码,添加删除角色等等
|
||||
//private SignInManager<result_user> _signInManager;//处理注册登录的相关逻辑
|
||||
|
||||
private IstudentBll _studentBll;
|
||||
public StudentController(ILogger<StudentController> logger, IstudentBll studentBll)
|
||||
{
|
||||
_studentBll = studentBll;
|
||||
_logger = logger;
|
||||
_logger.LogInformation("现在你进入了StudentController控制器");
|
||||
_studentBll = studentBll;
|
||||
}
|
||||
#region
|
||||
//关于身份认证配置使用:
|
||||
//在需要身份认证的控制器上打上 [Authorize] 特性标签
|
||||
#endregion
|
||||
//[HttpGet]
|
||||
//public async Task<IActionResult> IdentityTest()
|
||||
//{
|
||||
// //用户登入
|
||||
// var data = await _signInManager.PasswordSignInAsync("账号", "密码", false, false); //"是否记住密码","是否登入失败锁定用户"
|
||||
// //用户登出
|
||||
// await _signInManager.SignOutAsync();
|
||||
// //创建用户
|
||||
// var data2 = await _userManager.CreateAsync(new result_user { UserName="账户",Email="邮箱"},"密码");
|
||||
// //获取用户
|
||||
// var data3 = _userManager.Users;//这里可以使用Linq表达式Select
|
||||
// return Ok();
|
||||
//}
|
||||
|
||||
[HttpGet]
|
||||
public Result GetReids()
|
||||
{
|
||||
var data = CacheHelper.CacheWriter.GetCache<string>("key01");
|
||||
return Result.Success(data);
|
||||
}
|
||||
#region
|
||||
//下面,权限验证
|
||||
#endregion
|
||||
|
||||
//发送令牌
|
||||
[HttpGet]
|
||||
public Result Login(string role)
|
||||
{
|
||||
string userName = "admin";
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
|
||||
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
|
||||
new Claim(ClaimTypes.Name, userName),
|
||||
new Claim(ClaimTypes.Role,role)
|
||||
|
||||
};
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: JwtConst.Domain,
|
||||
audience: JwtConst.Domain,
|
||||
claims: claims,
|
||||
expires: DateTime.Now.AddMinutes(30),
|
||||
signingCredentials: creds);
|
||||
|
||||
var tokenData = new JwtSecurityTokenHandler().WriteToken(token);
|
||||
return Result.Success("欢迎你!管理员!").SetData(new { token = tokenData });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult Test()
|
||||
[Authorize(Policy = "myadmin")]//基于策略的验证
|
||||
public Result MyAdmin()
|
||||
{
|
||||
var data = _studentBll.GetAllEntities().ToList();
|
||||
return Content(Common.JsonFactory.JsonToString(data));
|
||||
return Result.Success("欢迎你!管理员!");
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize(Roles = "user")]//基于角色的验证
|
||||
public Result MyUser()
|
||||
{
|
||||
return Result.Success("欢迎你!游客!");
|
||||
}
|
||||
|
||||
#region
|
||||
//下面,经典的 增删改查 即为简易--Yi意框架
|
||||
//注意:请确保你的数据库中存在合理的数据
|
||||
#endregion
|
||||
[HttpGet]
|
||||
public async Task<Result> GetTest()//查
|
||||
{
|
||||
_logger.LogInformation("调用查方法");
|
||||
var data =await _studentBll.GetAllEntities().ToListAsync();
|
||||
return Result.Success().SetData(data);
|
||||
}
|
||||
[HttpGet]
|
||||
public Result AddTest()//增
|
||||
{
|
||||
_logger.LogInformation("调用增方法");
|
||||
List<student> students = new List<student>() { new student { name = "学生a" }, new student { name = "学生d" } };
|
||||
if (_studentBll.Add(students))
|
||||
{
|
||||
return Result.Success();
|
||||
}
|
||||
else
|
||||
{
|
||||
return Result.Error();
|
||||
}
|
||||
}
|
||||
[HttpGet]
|
||||
public Result RemoveTest()//删
|
||||
{
|
||||
_logger.LogInformation("调用删方法");
|
||||
if (_studentBll.Delete(u => u.name == "学生a"))
|
||||
{
|
||||
return Result.Success();
|
||||
}
|
||||
else
|
||||
{
|
||||
return Result.Error();
|
||||
}
|
||||
}
|
||||
[HttpGet]
|
||||
public Result UpdateTest()//改
|
||||
{
|
||||
_logger.LogInformation("调用改方法");
|
||||
if (_studentBll.Update(new student { id = 2, name = "学生a" }, "name"))
|
||||
{
|
||||
return Result.Success();
|
||||
}
|
||||
else
|
||||
{
|
||||
return Result.Error();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
76
CC.Yi.API/Extension/SwaggerExtension.cs
Normal file
76
CC.Yi.API/Extension/SwaggerExtension.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace CC.Yi.API.Extension
|
||||
{
|
||||
/// <summary>
|
||||
/// Swagger文档扩展方法
|
||||
/// </summary>
|
||||
public static class SwaggerExtension
|
||||
{
|
||||
public static IServiceCollection AddSwaggerService(this IServiceCollection services)
|
||||
{
|
||||
var apiInfo = new OpenApiInfo
|
||||
{
|
||||
Title = "Yi意框架-API接口",
|
||||
Version = "v1",
|
||||
Contact = new OpenApiContact { Name = "橙子", Email = "454313500@qq.com", Url = new System.Uri("https://jiftcc.com") }
|
||||
};
|
||||
#region 注册Swagger服务
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", apiInfo);
|
||||
|
||||
//添加注释服务
|
||||
//为 Swagger JSON and UI设置xml文档注释路径
|
||||
//获取应用程序所在目录(绝对路径,不受工作目录影响,建议采用此方法获取路径使用windwos&Linux)
|
||||
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
|
||||
var apiXmlPath = Path.Combine(basePath, @"ApiDoc.xml");//控制器层注释
|
||||
var entityXmlPath = Path.Combine(basePath, @"Model\ModelDoc.xml");//实体注释
|
||||
//c.IncludeXmlComments(apiXmlPath, true);//true表示显示控制器注释
|
||||
//c.IncludeXmlComments(entityXmlPath);
|
||||
|
||||
//添加控制器注释
|
||||
//c.DocumentFilter<SwaggerDocTag>();
|
||||
|
||||
//添加header验证信息
|
||||
//c.OperationFilter<SwaggerHeader>();
|
||||
//var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
|
||||
|
||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
|
||||
{
|
||||
Description = "文本框里输入从服务器获取的Token。格式为:Bearer + 空格+token",//JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"
|
||||
Name = "Authorization",////jwt默认的参数名称
|
||||
In = ParameterLocation.Header,////jwt默认存放Authorization信息的位置(请求头中)
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
});
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{ new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference()
|
||||
{
|
||||
Id = "Bearer",
|
||||
Type = ReferenceType.SecurityScheme
|
||||
}
|
||||
}, Array.Empty<string>() }
|
||||
});
|
||||
});
|
||||
#endregion
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static void UseSwaggerService(this IApplicationBuilder app)
|
||||
{
|
||||
//在 Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:
|
||||
// Enable middleware to serve generated Swagger as a JSON endpoint.
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "JwtTest v1"));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
21
CC.Yi.API/Filter/DbContextFilter.cs
Normal file
21
CC.Yi.API/Filter/DbContextFilter.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using CC.Yi.DAL;
|
||||
using CC.Yi.Model;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CC.Yi.API.Filter
|
||||
{
|
||||
public class DbContextFilter : ActionFilterAttribute
|
||||
{
|
||||
public override void OnActionExecuting(ActionExecutingContext filterContext)
|
||||
{
|
||||
|
||||
base.OnActionExecuting(filterContext);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,33 +2,29 @@
|
||||
using CC.Yi.Model;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace CC.Yi.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(DataContext))]
|
||||
[Migration("20210319112041_yi1")]
|
||||
partial class yi1
|
||||
[Migration("20210413063257_y1")]
|
||||
partial class y1
|
||||
{
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128)
|
||||
.HasAnnotation("ProductVersion", "5.0.4")
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
.HasAnnotation("ProductVersion", "5.0.5");
|
||||
|
||||
modelBuilder.Entity("CC.Yi.Model.student", b =>
|
||||
{
|
||||
b.Property<int>("id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int")
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("name")
|
||||
.HasColumnType("int");
|
||||
b.Property<string>("name")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("id");
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace CC.Yi.API.Migrations
|
||||
{
|
||||
public partial class yi1 : Migration
|
||||
public partial class y1 : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
@@ -10,9 +10,9 @@ namespace CC.Yi.API.Migrations
|
||||
name: "student",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
name = table.Column<int>(type: "int", nullable: false)
|
||||
id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
name = table.Column<string>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
@@ -2,7 +2,6 @@
|
||||
using CC.Yi.Model;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace CC.Yi.API.Migrations
|
||||
@@ -14,19 +13,16 @@ namespace CC.Yi.API.Migrations
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128)
|
||||
.HasAnnotation("ProductVersion", "5.0.4")
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
.HasAnnotation("ProductVersion", "5.0.5");
|
||||
|
||||
modelBuilder.Entity("CC.Yi.Model.student", b =>
|
||||
{
|
||||
b.Property<int>("id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int")
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("name")
|
||||
.HasColumnType("int");
|
||||
b.Property<string>("name")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("id");
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
using Autofac.Extensions.DependencyInjection;
|
||||
using CC.Yi.DAL;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Web;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -13,14 +17,49 @@ namespace CC.Yi.API
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
CreateHostBuilder(args).Build().Run();
|
||||
|
||||
|
||||
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
|
||||
try
|
||||
{
|
||||
logger.Debug("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Yi<59><69><EFBFBD><EFBFBD><EFBFBD>ܡ<EFBFBD><DCA1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
|
||||
var host = CreateHostBuilder(args).Build();
|
||||
//var scope = host.Services.CreateScope();
|
||||
//var services = scope.ServiceProvider;
|
||||
//var context = services.GetRequiredService<Model.DataContext>();//<2F><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>
|
||||
//DbContentFactory.Initialize(context);//<2F><><EFBFBD>þ<EFBFBD>̬<EFBFBD><EFBFBD><E0B7BD>ע<EFBFBD><D7A2>
|
||||
host.Run();
|
||||
logger.Info("Yi<59><69><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɹ<EFBFBD><C9B9><EFBFBD>");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
//NLog: catch setup errors
|
||||
logger.Error(exception, "Stopped program because of exception");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
|
||||
NLog.LogManager.Shutdown();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
});
|
||||
|
||||
webBuilder.UseUrls("http://*:19000").UseStartup<Startup>();
|
||||
}).UseServiceProviderFactory(new AutofacServiceProviderFactory())
|
||||
.ConfigureLogging(logging =>
|
||||
{
|
||||
// logging.ClearProviders(); // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>п<EFBFBD><D0BF><EFBFBD>̨<EFBFBD><CCA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
|
||||
}).UseNLog();//<2F><><EFBFBD><EFBFBD>nlog<6F><67>־<EFBFBD><D6BE><EFBFBD><EFBFBD>
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
|
||||
using Autofac;
|
||||
using Autofac.Extras.DynamicProxy;
|
||||
using CC.Yi.API.Extension;
|
||||
using CC.Yi.BLL;
|
||||
using CC.Yi.Common.Castle;
|
||||
using CC.Yi.Common.Jwt;
|
||||
using CC.Yi.DAL;
|
||||
using CC.Yi.IBLL;
|
||||
using CC.Yi.IDAL;
|
||||
using CC.Yi.Model;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.HttpsPolicy;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CC.Yi.API
|
||||
@@ -33,20 +41,80 @@ namespace CC.Yi.API
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
|
||||
services.AddControllers();
|
||||
services.AddSwaggerGen(c =>
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CC.Yi.API", Version = "v1" });
|
||||
//<2F><><EFBFBD>û<EFBFBD><C3BB>ڲ<EFBFBD><DAB2>Ե<EFBFBD><D4B5><EFBFBD>֤
|
||||
options.AddPolicy("myadmin", policy =>
|
||||
policy.RequireRole("admin"));
|
||||
});
|
||||
string connection = Configuration["ConnectionStringBySQL"];
|
||||
|
||||
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options => {
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤Issuer
|
||||
ValidateAudience = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤Audience
|
||||
ValidateLifetime = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤ʧЧʱ<D0A7><CAB1>
|
||||
ClockSkew = TimeSpan.FromSeconds(30),
|
||||
ValidateIssuerSigningKey = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤SecurityKey
|
||||
ValidAudience = JwtConst.Domain,//Audience
|
||||
ValidIssuer = JwtConst.Domain,//Issuer<65><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǰ<EFBFBD><C7B0>ǩ<EFBFBD><C7A9>jwt<77><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey))//<2F>õ<EFBFBD>SecurityKey
|
||||
};
|
||||
});
|
||||
services.AddControllers();
|
||||
services.AddSwaggerService();
|
||||
services.AddSession();
|
||||
|
||||
//<2F><><EFBFBD>ù<EFBFBD><C3B9><EFBFBD><EFBFBD><EFBFBD>
|
||||
Action<MvcOptions> filters = new Action<MvcOptions>(r => {
|
||||
//r.Filters.Add(typeof(DbContextFilter));
|
||||
});
|
||||
services.AddMvc(filters);
|
||||
string connection1 = Configuration["ConnectionStringBySQL"];
|
||||
string connection2 = Configuration["ConnectionStringByMySQL"];
|
||||
string connection3 = Configuration["ConnectionStringBySQLite"];
|
||||
services.AddDbContext<DataContext>(options =>
|
||||
{
|
||||
options.UseSqlServer(connection, b => b.MigrationsAssembly("CC.Yi.API"));//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݿ<EFBFBD>
|
||||
options.UseSqlite(connection3, b => b.MigrationsAssembly("CC.Yi.API"));//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݿ<EFBFBD>
|
||||
});
|
||||
services.AddScoped(typeof(IBaseDal<>), typeof(BaseDal<>));
|
||||
services.AddScoped(typeof(IstudentBll), typeof(studentBll));
|
||||
|
||||
|
||||
//<2F><><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>ת<EFBFBD><D7AA><EFBFBD><EFBFBD>Autofac
|
||||
//services.AddScoped(typeof(IBaseDal<>), typeof(BaseDal<>));
|
||||
//services.AddScoped(typeof(IstudentBll), typeof(studentBll));
|
||||
|
||||
|
||||
|
||||
//<2F><><EFBFBD><EFBFBD>Identity<74><79><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤
|
||||
//services.AddIdentity<result_user, IdentityRole>(options =>
|
||||
// {
|
||||
// options.Password.RequiredLength = 6;//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̳<EFBFBD><CCB3><EFBFBD>
|
||||
// options.Password.RequireDigit = false;//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
// options.Password.RequireLowercase = false;//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Сд<D0A1><D0B4>ĸ
|
||||
// options.Password.RequireNonAlphanumeric = false;//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD>
|
||||
// options.Password.RequireUppercase = false;//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>д<EFBFBD><D0B4>ĸ
|
||||
// //options.User.RequireUniqueEmail = false;//ע<><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD>Բ<EFBFBD><D4B2>ظ<EFBFBD>
|
||||
// //options.User.AllowedUserNameCharacters="abcd"//<2F><><EFBFBD><EFBFBD>ֻ<EFBFBD><D6BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD>
|
||||
//}).AddEntityFrameworkStores<DataContext>().AddDefaultTokenProviders();
|
||||
services.AddCors(options => options.AddPolicy("CorsPolicy",//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
builder =>
|
||||
{
|
||||
builder.AllowAnyMethod()
|
||||
.SetIsOriginAllowed(_ => true)
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
}));
|
||||
}
|
||||
|
||||
//<2F><>ʼ<EFBFBD><CABC>ʹ<EFBFBD>ú<EFBFBD><C3BA><EFBFBD>
|
||||
private void InitData(IServiceProvider serviceProvider)
|
||||
{
|
||||
//var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
|
||||
|
||||
//var context = serviceScope.ServiceProvider.GetService<DataContext>();
|
||||
//DbContentFactory.Initialize(context);//<2F><><EFBFBD>þ<EFBFBD>̬<EFBFBD><EFBFBD><E0B7BD>ע<EFBFBD><D7A2>
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
@@ -55,20 +123,22 @@ namespace CC.Yi.API
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CC.Yi.API v1"));
|
||||
app.UseSwaggerService();
|
||||
}
|
||||
|
||||
|
||||
app.UseCors("CorsPolicy");
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseSession();
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapControllers();
|
||||
});
|
||||
InitData(app.ApplicationServices);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
23
CC.Yi.API/T4Startup.cs
Normal file
23
CC.Yi.API/T4Startup.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using Autofac;
|
||||
using Autofac.Extras.DynamicProxy;
|
||||
using CC.Yi.BLL;
|
||||
using CC.Yi.Common.Castle;
|
||||
using CC.Yi.DAL;
|
||||
using CC.Yi.IBLL;
|
||||
using CC.Yi.IDAL;
|
||||
using System;
|
||||
|
||||
|
||||
namespace CC.Yi.API
|
||||
{
|
||||
public partial class Startup
|
||||
{
|
||||
//动态 面向AOP思想的依赖注入 Autofac
|
||||
public void ConfigureContainer(ContainerBuilder builder)
|
||||
{
|
||||
builder.RegisterType(typeof(CustomAutofacAop));
|
||||
builder.RegisterGeneric(typeof(BaseDal<>)).As(typeof(IBaseDal<>));
|
||||
builder.RegisterType<studentBll>().As<IstudentBll>().EnableInterfaceInterceptors();//表示注入前后要执行Castle,AOP
|
||||
}
|
||||
}
|
||||
}
|
||||
40
CC.Yi.API/T4Startup.tt
Normal file
40
CC.Yi.API/T4Startup.tt
Normal file
@@ -0,0 +1,40 @@
|
||||
<#@ template debug="false" hostspecific="true" language="C#" #>
|
||||
<#@ assembly name="System.Core" #>
|
||||
<#@ import namespace="System.Linq" #>
|
||||
<#@ import namespace="System.Text" #>
|
||||
<#@ import namespace="System.Collections.Generic" #>
|
||||
<#@ import namespace="System.IO" #>
|
||||
<#@ output extension=".cs" #>
|
||||
<#
|
||||
string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)");//获取解决方案路径
|
||||
string txt;
|
||||
StreamReader sr = new StreamReader(solutionsPath+@"\T4Model\T4Model.txt");
|
||||
txt=sr.ReadToEnd();
|
||||
sr.Close();
|
||||
string[] ModelData= txt.Split(',');
|
||||
#>
|
||||
using Autofac;
|
||||
using Autofac.Extras.DynamicProxy;
|
||||
using CC.Yi.BLL;
|
||||
using CC.Yi.Common.Castle;
|
||||
using CC.Yi.DAL;
|
||||
using CC.Yi.IBLL;
|
||||
using CC.Yi.IDAL;
|
||||
using System;
|
||||
|
||||
|
||||
namespace CC.Yi.API
|
||||
{
|
||||
public partial class Startup
|
||||
{
|
||||
//动态 面向AOP思想的依赖注入 Autofac
|
||||
public void ConfigureContainer(ContainerBuilder builder)
|
||||
{
|
||||
builder.RegisterType(typeof(CustomAutofacAop));
|
||||
builder.RegisterGeneric(typeof(BaseDal<>)).As(typeof(IBaseDal<>));
|
||||
<# foreach(string k in ModelData){#>
|
||||
builder.RegisterType<<#=k #>Bll>().As<I<#=k #>Bll>().EnableInterfaceInterceptors();//表示注入前后要执行Castle,AOP
|
||||
<# } #>
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
CC.Yi.API/YIDB.db
Normal file
BIN
CC.Yi.API/YIDB.db
Normal file
Binary file not shown.
@@ -7,6 +7,8 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ConnectionStringBySQL": "server=.;Database=cctest;UId=sa;PWD=Qz52013142020.",
|
||||
"ConnectionStringByMySQL": "Data Source=49.235.212.122;Database=GraduationProject;User ID=root;Password=Qz52013142020.;pooling=true;port=3306;sslmode=none;CharSet=utf8;"
|
||||
|
||||
"ConnectionStringBySQL": "server=.;Database=YIDB;UId=sa;PWD=52013142020.",
|
||||
"ConnectionStringByMySQL": "Data Source=.;Database=YIDB;User ID=root;Password=52013142020.;pooling=true;port=3306;sslmode=none;CharSet=utf8;",
|
||||
"ConnectionStringBySQLite": "Filename=YIDB.db"
|
||||
}
|
||||
|
||||
35
CC.Yi.API/nlog.config
Normal file
35
CC.Yi.API/nlog.config
Normal file
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true"
|
||||
throwExceptions="false"
|
||||
internalLogLevel="Warn"
|
||||
internalLogFile="Logs\internal-nlog.txt">
|
||||
|
||||
<!-- enable asp.net core layout renderers -->
|
||||
<extensions>
|
||||
<add assembly="NLog.Web.AspNetCore"/>
|
||||
</extensions>
|
||||
|
||||
<targets>
|
||||
<!-- 写入文件配置 -->
|
||||
<!-- write logs to file -->
|
||||
<target xsi:type="File" name="allfile" fileName="Logs\nlog-all-${shortdate}.log"
|
||||
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring} ${newline}" />
|
||||
|
||||
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
|
||||
<target xsi:type="File" name="ownFile-web" fileName="Logs\nlog-own-${shortdate}.log"
|
||||
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action} ${newline}" />
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
<!--All logs, including from Microsoft-->
|
||||
<!--minlevel 改为Trace 跟踪全部 Error 只捕获异常-->
|
||||
<logger name="*" minlevel="Trace" writeTo="allfile" />
|
||||
|
||||
<!--Skip non-critical Microsoft logs and so log only own logs-->
|
||||
<logger name="Microsoft.*" maxlevel="Info" final="true" />
|
||||
<!-- BlackHole without writeTo -->
|
||||
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
|
||||
</rules>
|
||||
</nlog>
|
||||
Reference in New Issue
Block a user