diff --git a/.gitignore b/.gitignore index 3e8a1553fcff7845c779d3cb8014e151a9931506..34aa044d6fa4a8ff68d98f8af2854e20fb8aa27b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,341 +1,4 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ -# ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true -**/wwwroot/lib/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb +.vscode +.vs +bin +obj \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api.sln" new file mode 100644 index 0000000000000000000000000000000000000000..2f92ebd9bda9292e2c0238f7ef2c03e5e1a019a9 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api.sln" @@ -0,0 +1,18 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..da2013171f9ef687974a4076fa92b8f3dfb6dd48 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,78 @@ +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using MyWebApi.Api.Entity; +using System.Linq; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase { + [HttpGet] + // public dynamic Get(){ + // return "唯独你没懂"; + // } + + [HttpGet] + public IEnumerable Get(){ + var users = GetUsers(); + return users; + } + [HttpGet("{id}")] + public dynamic Get(int id){ + var users = GetUsers(); + var user = users.Where(x=>x.Id==id).FirstOrDefault(); + return user; + } + + + [HttpPost] + public dynamic Post(dynamic model){ + + return new{ + Data=model, + Msg="成功了" + }; + } + + [HttpPut("{id}")] + public dynamic Put(int id,dynamic model){ + + return new{ + Data=model, + Msg=string.Format("要修改的Id为{0},",id) + }; + } + + [HttpDelete("{id}")] + public dynamic Delete(int id,dynamic model){ + + return new{ + Data=model, + Msg=string.Format("要删除的Id为{0},",id) + }; + } + + + private IEnumerable GetUsers(){ + var users = new List{ + new Users{ + Id=1, + UserName="你好", + PassWord="确实好啊" + }, + new Users{ + Id=2, + UserName="真的吗", + PassWord="不啊" + }, + new Users{ + Id=3, + UserName="可以吗", + PassWord="我觉得不行" + }, + }; + return users; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..4e01cb2ad30d97a1d82b387fd068eb71d3773625 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Data/ShowDb.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Data/ShowDb.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d8fcc9b0eb8d9be0c397937aa37de886b5a2d211 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Data/ShowDb.cs" @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using MyWebApi.Api.Entity; + +namespace MyWebApi.Api.Db +{ + public class ShowDb : DbContext + { + public DbSet Users { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(@"server=.;database=ShowDb;uid=sa;pwd=123456;"); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/BaseEntity.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/BaseEntity.cs" new file mode 100644 index 0000000000000000000000000000000000000000..b8c3337032199e320986e2cf02379588c01f4ce0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/BaseEntity.cs" @@ -0,0 +1,15 @@ +using System; + +namespace MyWebApi.Api.Entity +{ + public abstract class BaseEntity + { + public int Id{get;set;} + public bool IsActived { get; set; } + public bool IsDeleted { get; set; } + public DateTime CreatedTime { get; set; } + public DateTime UpdatedTime { get; set; } + public int DisplayOrder { get; set; } + public string Remarks { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/Roles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/Roles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..0e8a360b5dab81f94cba804073368e6e15880175 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/Roles.cs" @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace MyWebApi.Api.Entity +{ + public class Roles : BaseEntity + { + public string RoleName{get;set;} + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/UserRoles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/UserRoles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..3769546994af2cc51eee61542257c188e985e306 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/UserRoles.cs" @@ -0,0 +1,13 @@ +using System; + +namespace MyWebApi.Api.Entity +{ + public class UserRoles : BaseEntity + { + public int UserId { get; set; } + public int RoleId { get; set; } + + public virtual Users User { get; set; } + public virtual Roles Role { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..b97cb408346d36bed0e8864022a2facf5fb1680f --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Entity/Users.cs" @@ -0,0 +1,10 @@ +using System; + +namespace MyWebApi.Api.Entity +{ + public class Users{ + public int Id{get;set;} + public String UserName{get;set;} + public string PassWord{get;set;} + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/20210629024032_InitialCreate.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/20210629024032_InitialCreate.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..bc23c650f1e443b696d60c85a8a675264ec86cf7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/20210629024032_InitialCreate.Designer.cs" @@ -0,0 +1,43 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MyWebApi.Api.Db; + +namespace MyWebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210629024032_InitialCreate")] + partial class InitialCreate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("MyWebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("PassWord") + .HasColumnType("nvarchar(max)"); + + b.Property("UserName") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/20210629024032_InitialCreate.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/20210629024032_InitialCreate.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d5ff20be4197359722a420552246ffc2fc8e937f --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/20210629024032_InitialCreate.cs" @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace MyWebApi.Api.Migrations +{ + public partial class InitialCreate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserName = table.Column(type: "nvarchar(max)", nullable: true), + PassWord = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/ShowDbModelSnapshot.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/ShowDbModelSnapshot.cs" new file mode 100644 index 0000000000000000000000000000000000000000..83a875e2f3fec4cdfcb67011320d872f6c3c91ab --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Migrations/ShowDbModelSnapshot.cs" @@ -0,0 +1,41 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MyWebApi.Api.Db; + +namespace MyWebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + partial class ShowDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("MyWebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("PassWord") + .HasColumnType("nvarchar(max)"); + + b.Property("UserName") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/MyWebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/MyWebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..a1ec8beb2cbf668109f82c63e92056b74f2cf7c3 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/MyWebApi.Api.csproj" @@ -0,0 +1,17 @@ + + + + netcoreapp3.1 + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/ParamModel/NewUser.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/ParamModel/NewUser.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5a9820b56bc3e9372c379041102652ceb510ea33 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/ParamModel/NewUser.cs" @@ -0,0 +1,7 @@ +namespace MyWebApi.Api.ParamModel +{ + public class NewUser{ + public string UserName{get;set;} + public string PassWord{get;set;} + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..49aa87cb41459c340fb650723ac6fe3b30053fe7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..549dce5e9757fe170af7b46626817b8f8b348413 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:62960", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "MyWebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..32ca4a27285646336cfd5e7693fddac624622efe --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/Startup.cs" @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddControllers(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..fe20bc77370d51a15a47b8f8d7cee03311599883 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace MyWebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..d9d9a9bff6fd6f3ee7ea00de958f135a4a28c6e6 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/MyWebApi.Api/appsettings.json" @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..95d5757152574d30b7105744cc823ae82da9cadb --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api/api.http" @@ -0,0 +1,35 @@ +###Get 获取 + +GET http://localhost:5000/users HTTP/1.1 + +### +GET http://localhost:5000/users/2 HTTP/1.1 + + +### Post 添加 + +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"里", + "PassWord":"123" +} +### Put 修改 + +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"这里", + "PassWord":"123" +} +### Delete 删除 + +DELETE http://localhost:5000/users/2 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"哪里", + "PassWord":"123" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/.vscode/launch.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/.vscode/launch.json" new file mode 100644 index 0000000000000000000000000000000000000000..968653266b8f8830588c68f1405556726d7a0289 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/.vscode/launch.json" @@ -0,0 +1,17 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "启动程序", + "skipFiles": [ + "/**" + ], + "program": "${file}" + } + ] +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api.sln" new file mode 100644 index 0000000000000000000000000000000000000000..2f92ebd9bda9292e2c0238f7ef2c03e5e1a019a9 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api.sln" @@ -0,0 +1,18 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..3cc13b10820e77e3dcb9a4e0c2770ebc22949d60 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,78 @@ +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using MyApi.Api.Entity; +using System.Linq; + +namespace MyApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase { + [HttpGet] + // public dynamic Get(){ + // return "唯独你没懂"; + // } + + [HttpGet] + public IEnumerable Get(){ + var users = GetUsers(); + return users; + } + [HttpGet("{id}")] + public dynamic Get(int id){ + var users = GetUsers(); + var user = users.Where(x=>x.Id==id).FirstOrDefault(); + return user; + } + + + [HttpPost] + public dynamic Post(dynamic model){ + + return new{ + Data=model, + Msg="成功了" + }; + } + + [HttpPut("{id}")] + public dynamic Put(int id,dynamic model){ + + return new{ + Data=model, + Msg=string.Format("要修改的Id为{0},",id) + }; + } + + [HttpDelete("{id}")] + public dynamic Delete(int id,dynamic model){ + + return new{ + Data=model, + Msg=string.Format("要删除的Id为{0},",id) + }; + } + + + private IEnumerable GetUsers(){ + var users = new List{ + new Users{ + Id=1, + UserName="你好", + PassWord="确实好啊" + }, + new Users{ + Id=2, + UserName="真的吗", + PassWord="不啊" + }, + new Users{ + Id=3, + UserName="可以吗", + PassWord="我觉得不行" + }, + }; + return users; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..4e01cb2ad30d97a1d82b387fd068eb71d3773625 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..995f8ddc036e6aaef7da38762ded3fa94e982324 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Entity/Users.cs" @@ -0,0 +1,10 @@ +using System; + +namespace MyApi.Api.Entity +{ + public class Users{ + public int Id{get;set;} + public String UserName{get;set;} + public string PassWord{get;set;} + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/MyWebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/MyWebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..d12c450b7be925549ec1738db82e35481fa8cbbc --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/MyWebApi.Api.csproj" @@ -0,0 +1,8 @@ + + + + netcoreapp3.1 + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..49aa87cb41459c340fb650723ac6fe3b30053fe7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..549dce5e9757fe170af7b46626817b8f8b348413 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:62960", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "MyWebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..32ca4a27285646336cfd5e7693fddac624622efe --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/Startup.cs" @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddControllers(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..fe20bc77370d51a15a47b8f8d7cee03311599883 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace MyWebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..d9d9a9bff6fd6f3ee7ea00de958f135a4a28c6e6 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/MyWebApi.Api/appsettings.json" @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..9fbde2b38b5d0d6ddf1765370aafe18f6fe9a467 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api0/api.http" @@ -0,0 +1,35 @@ +###Get + +GET http://localhost:5000/users HTTP/1.1 + +### +GET http://localhost:5000/users/2 HTTP/1.1 + + +### Post + +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"里", + "PassWord":"123" +} +### Put + +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"这里", + "PassWord":"123" +} +### Delete + +DELETE http://localhost:5000/users/2 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"哪里", + "PassWord":"123" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api.sln" new file mode 100644 index 0000000000000000000000000000000000000000..2f92ebd9bda9292e2c0238f7ef2c03e5e1a019a9 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api.sln" @@ -0,0 +1,18 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..166fecdd40160c49fae1de4f0ef10e3419420ddc --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using Admin3000.Backend.Api.Entity; +using Microsoft.AspNetCore.Mvc; +using System.Linq; +using MyWebApi.Api.ParamModel; +using Newtonsoft.Json; +using MyWebApi.Api.Repository; + + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase + { + private Api.Db.MyWebApiDb db=new Api.Db.MyWebApiDb(); + private IRepository _usersRespository=new EfRepository(); + + [HttpGet] + public dynamic Get() + { + + var users = _usersRespository.Table.ToList(); + return new { + Code =1000, + Data =users, + Msg ="获取用户列表成功^_^" + }; + } + + [HttpGet("{id}")] + public dynamic Get(int id) + { + var user = db.Users.Where(x => x.Id == id).FirstOrDefault(); + return user; + } + + [HttpPost] + public string Post(NewUser model) + { + JsonSerializerSettings settings = new JsonSerializerSettings(); + // settings.MissingMemberHandling = MissingMemberHandling.Ignore; + settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + var user = new Users + { + Username = model.Username, + Password = model.Password + }; + + db.Users.Add(user); + db.SaveChanges(); + + var res = new + { + Code = 1000, + Data = user, + Msg = "创建用户成功" + }; + return JsonConvert.SerializeObject(res, settings); + } + + [HttpPut("{id}")] + public dynamic Put(int id, NewUser model) + { + var user = db.Users.Where(x => x.Id == id).FirstOrDefault(); + + if (user != null) + { + user.Username = model.Username; + user.Password = model.Password; + user.UpdatedTime=DateTime.Now; + db.Update(user); + db.SaveChanges(); + return new + { + Code = 1000, + Data = user, + Msg = string.Format("你修改的用户的id为:{0},已经修改成功,请注意查收", id) + }; + } + else + { + return new + { + Code = 104, + Data = "", + Msg = "指定Id的用户不存在,请确认后重试" + }; + } + } + + [HttpDelete("{id}")] + public dynamic Delete(int id) + { + var user = db.Users.Where(x => x.Id == id).FirstOrDefault(); + if (user != null) + { + db.Users.Remove(user); + db.SaveChanges(); + return new + { + Code = 1000, + Msg = string.Format("删除指定id为{0}的用户成功", id) + }; + } + else + { + return new + { + Code = 104, + Data = "", + Msg = "指定Id的用户不存在,请确认后重试" + }; + } + + } + + private IEnumerable GetUsers() + { + var users = + new List { + new Users { + Id = 1, + Username = "admin", + Password = "芝麻开门" + }, + new Users { + Id = 2, + Username = "超级管理员", + Password = "芝麻开门" + }, + new Users { + Id = 3, + Username = "普通用户", + Password = "芝麻开门" + } + }; + + return users; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..4e01cb2ad30d97a1d82b387fd068eb71d3773625 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Data/ShowDb.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Data/ShowDb.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d8fcc9b0eb8d9be0c397937aa37de886b5a2d211 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Data/ShowDb.cs" @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using MyWebApi.Api.Entity; + +namespace MyWebApi.Api.Db +{ + public class ShowDb : DbContext + { + public DbSet Users { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(@"server=.;database=ShowDb;uid=sa;pwd=123456;"); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/BaseEntity.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/BaseEntity.cs" new file mode 100644 index 0000000000000000000000000000000000000000..b8c3337032199e320986e2cf02379588c01f4ce0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/BaseEntity.cs" @@ -0,0 +1,15 @@ +using System; + +namespace MyWebApi.Api.Entity +{ + public abstract class BaseEntity + { + public int Id{get;set;} + public bool IsActived { get; set; } + public bool IsDeleted { get; set; } + public DateTime CreatedTime { get; set; } + public DateTime UpdatedTime { get; set; } + public int DisplayOrder { get; set; } + public string Remarks { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/Roles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/Roles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..0e8a360b5dab81f94cba804073368e6e15880175 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/Roles.cs" @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace MyWebApi.Api.Entity +{ + public class Roles : BaseEntity + { + public string RoleName{get;set;} + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/UserRoles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/UserRoles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..3769546994af2cc51eee61542257c188e985e306 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/UserRoles.cs" @@ -0,0 +1,13 @@ +using System; + +namespace MyWebApi.Api.Entity +{ + public class UserRoles : BaseEntity + { + public int UserId { get; set; } + public int RoleId { get; set; } + + public virtual Users User { get; set; } + public virtual Roles Role { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..b97cb408346d36bed0e8864022a2facf5fb1680f --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Entity/Users.cs" @@ -0,0 +1,10 @@ +using System; + +namespace MyWebApi.Api.Entity +{ + public class Users{ + public int Id{get;set;} + public String UserName{get;set;} + public string PassWord{get;set;} + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/20210629024032_InitialCreate.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/20210629024032_InitialCreate.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..bc23c650f1e443b696d60c85a8a675264ec86cf7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/20210629024032_InitialCreate.Designer.cs" @@ -0,0 +1,43 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MyWebApi.Api.Db; + +namespace MyWebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210629024032_InitialCreate")] + partial class InitialCreate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("MyWebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("PassWord") + .HasColumnType("nvarchar(max)"); + + b.Property("UserName") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/20210629024032_InitialCreate.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/20210629024032_InitialCreate.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d5ff20be4197359722a420552246ffc2fc8e937f --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/20210629024032_InitialCreate.cs" @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace MyWebApi.Api.Migrations +{ + public partial class InitialCreate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserName = table.Column(type: "nvarchar(max)", nullable: true), + PassWord = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/ShowDbModelSnapshot.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/ShowDbModelSnapshot.cs" new file mode 100644 index 0000000000000000000000000000000000000000..83a875e2f3fec4cdfcb67011320d872f6c3c91ab --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Migrations/ShowDbModelSnapshot.cs" @@ -0,0 +1,41 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MyWebApi.Api.Db; + +namespace MyWebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + partial class ShowDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("MyWebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("PassWord") + .HasColumnType("nvarchar(max)"); + + b.Property("UserName") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/MyWebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/MyWebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..a1ec8beb2cbf668109f82c63e92056b74f2cf7c3 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/MyWebApi.Api.csproj" @@ -0,0 +1,17 @@ + + + + netcoreapp3.1 + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/ParamModel/NewUser.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/ParamModel/NewUser.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5a9820b56bc3e9372c379041102652ceb510ea33 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/ParamModel/NewUser.cs" @@ -0,0 +1,7 @@ +namespace MyWebApi.Api.ParamModel +{ + public class NewUser{ + public string UserName{get;set;} + public string PassWord{get;set;} + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..49aa87cb41459c340fb650723ac6fe3b30053fe7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..549dce5e9757fe170af7b46626817b8f8b348413 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:62960", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "MyWebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..32ca4a27285646336cfd5e7693fddac624622efe --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/Startup.cs" @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace MyWebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddControllers(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..fe20bc77370d51a15a47b8f8d7cee03311599883 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace MyWebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..d9d9a9bff6fd6f3ee7ea00de958f135a4a28c6e6 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/MyWebApi.Api/appsettings.json" @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..95d5757152574d30b7105744cc823ae82da9cadb --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/MyWebApi.Api23/api.http" @@ -0,0 +1,35 @@ +###Get 获取 + +GET http://localhost:5000/users HTTP/1.1 + +### +GET http://localhost:5000/users/2 HTTP/1.1 + + +### Post 添加 + +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"里", + "PassWord":"123" +} +### Put 修改 + +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"这里", + "PassWord":"123" +} +### Delete 删除 + +DELETE http://localhost:5000/users/2 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"哪里", + "PassWord":"123" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..06e344aa9f669f03cb57a3f683f4421347e617ab --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,198 @@ +using System; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using WebApi.Api.Entity; +using System.Linq; +using Newtonsoft.Json; +using WebApi.Api.ParamModel; +using WebApi.Api.Repository; +using WebApi.Api.Utils; +using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Authorization; + +namespace MyWebApi.Api.Controllers +{ + [Authorize] + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase + { + private IRepository _usersRespository; + private TokenParameter _tokenParameter; + private readonly IConfiguration _configuration; + public UsersController(IConfiguration configuration, IRepository usersRespository) + { + _configuration = configuration; + _usersRespository = usersRespository; + _tokenParameter = _configuration.GetSection("TokenParameter").Get(); + } + + [HttpGet] + public dynamic Get() + { + var users = _usersRespository.Table.ToList(); + return new + { + Code = 1020, + Data = users, + Msg = "获取用户列表成功" + }; + } + + [HttpGet("{id}")] + public dynamic Get(int id) + { + var user = _usersRespository.GetById(id); + // return user; + if (user == null) + { + return new + { + Code = 1000, + Data = "", + Msg = "指定用户不存在" + }; + + } + return new + { + Code = 1000, + Data = user, + Msg = "获取用户列表成功" + }; + } + + [AllowAnonymous] + [HttpPost] + public string Post(NewUser model) + { + JsonSerializerSettings settings = new JsonSerializerSettings(); + + settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + var user = new Users + { + Username = model.Username, + Password = model.Password + }; + + _usersRespository.Insert(user); + + var res = new + { + Code = 1000, + Data = user, + Msg = "创建用户成功" + }; + return JsonConvert.SerializeObject(res, settings); + } + + [AllowAnonymous] + [HttpPut("{id}")] + public dynamic Put(int id, NewUser model) + { + var user = _usersRespository.GetById(id); + + if (user != null) + { + user.Username = model.Username; + user.Password = model.Password; + user.UpdatedTime = DateTime.Now; + _usersRespository.Update(user); + return new + { + Code = 1000, + Data = user, + Msg = string.Format("你修改的用户的id为:{0},已经修改成功,请注意查收", id) + }; + } + else + { + return new + { + Code = 104, + Data = "", + Msg = "指定Id的用户不存在,请确认后重试" + }; + } + } + + + [HttpDelete("{id}")] + public dynamic Delete(int id) + { + var user = _usersRespository.GetById(id); + if (user != null) + { + _usersRespository.Delete(id); + return new + { + Code = 1000, + Msg = string.Format("删除指定id为{0}的用户成功", id) + }; + } + else + { + return new + { + Code = 1000, + Data = "", + Msg = "指定id的用户不存在,请确认重试" + }; + } + } + + private IEnumerable GetUsers() + { + var users = new List{ + new Users{ + Id=1, + Username="你好", + Password="确实好啊" + }, + new Users{ + Id=2, + Username="真的吗", + Password="不啊" + }, + new Users{ + Id=3, + Username="可以吗", + Password="我觉得不行" + }, + }; + return users; + } + + [AllowAnonymous] + [HttpPost, Route("token")] + public dynamic GetToken(NewUser model) + { + var username = model.Username.Trim(); + var password = model.Password.Trim(); + + var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault(); + + if (user == null) + { + return new + { + Code = 1001, + Data = user, + Msg = "用户名或密码不正确,请核对后重试" + }; + } + + var token = TokenHelper.GenerateToekn(_tokenParameter, user); + var refreshToken = "12235"; + + var res = new + { + Code = 1000, + Data = new { Token = token, RefreshToken = refreshToken }, + Msg = "用户登录成功" + }; + return res; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d2b595033ea0a3f002f879ebe5ecf13ac4c01152 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Data/ShowDb.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Data/ShowDb.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5e6a9d25c5e6092601e61f0784ecd9df781b41ed --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Data/ShowDb.cs" @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; + +namespace WebApi.Api.Db +{ + public class ShowDb : DbContext + { + // 因为我们使用AddDbContext到容器,所以此处必须得有带参数的构造函数 + public ShowDb(DbContextOptions options) : base(options) + { + + } + + public DbSet Users { get; set; } + public DbSet Roles { get; set; } + public DbSet UserRoles { get; set; } + public DbSet AuditInfo { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(@"server=.;database=ShowDb;uid=sa;pwd=123456;"); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/AuditInfo.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/AuditInfo.cs" new file mode 100644 index 0000000000000000000000000000000000000000..74e81c343060138d8c0fab7601ce00becef42b49 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/AuditInfo.cs" @@ -0,0 +1,56 @@ +using System; + +namespace WebApi.Api.Entity +{ + public class AuditInfo : BaseEntity + { + /// + /// 调用参数 + /// + public string Parameters { get; set; } + /// + /// 浏览器信息 + /// + public string BrowserInfo { get; set; } + /// + /// 客户端信息 + /// + public string ClientName { get; set; } + /// + /// 客户端IP地址 + /// + public string ClientIpAddress { get; set; } + /// + /// 执行耗时 + /// + public int ExecutionDuration { get; set; } + /// + /// 执行时间 + /// + public DateTime ExecutionTime { get; set; } + /// + /// 返回内容 + /// + public string ReturnValue { get; set; } + /// + /// 异常对象 + /// + public string Exception { get; set; } + /// + /// 方法名 + /// + public string MethodName { get; set; } + /// + /// 服务名 + /// + public string ServiceName { get; set; } + /// + /// 调用者信息 + /// + public string UserInfo { get; set; } + /// + /// 自定义数据 + /// + public string CustomData { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/BaseEntity.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/BaseEntity.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5816e54e01de59ac6335eeeb903dc7c0b54deec0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/BaseEntity.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api.Entity +{ + public abstract class BaseEntity + { + public int Id { get; set; } + public bool IsActived { get; set; } + public bool IsDeleted { get; set; } + public DateTime CreatedTime { get; set; } + public DateTime UpdatedTime { get; set; } + public int DisplayOrder { get; set; } + public string Remarks { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/Roles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/Roles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..0f178913d9786955db8ff83f9507e0538e0a657d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/Roles.cs" @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Roles : BaseEntity + { + public string RoleName { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/UserRoles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/UserRoles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..67be0a855feb6fffd2604dfc58613a4749669629 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/UserRoles.cs" @@ -0,0 +1,12 @@ +using System; + +namespace WebApi.Api.Entity +{ + public class UserRoles : BaseEntity + { + public int UserId { get; set; } + public int RoleId { get; set; } + public virtual Users User { get; set; } + public virtual Roles Role { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..96b6787fa69f7876ea4b37d6e038fa7ea9b83ef9 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Entity/Users.cs" @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Users : BaseEntity + { + public string Username { get; set; } + public string Password { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Filters/AuditLogActionFilter.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Filters/AuditLogActionFilter.cs" new file mode 100644 index 0000000000000000000000000000000000000000..f172f9aa1b86308ad09691e4742d29ea31d4d74e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Filters/AuditLogActionFilter.cs" @@ -0,0 +1,148 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using WebApi.Api.Entity; +using WebApi.Api.Repository; + +namespace WebApi.Api.Fliters +{ + public class AuditLogActionFilter : IAsyncActionFilter + { + private readonly IRepository _auditLogService; + + public AuditLogActionFilter( + IRepository auditLogService + ) + { + _auditLogService = auditLogService; + } + + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + // 判断是否写日志 + if (!ShouldSaveAudit(context)) + { + await next(); + return; + } + //接口Type + var type = (context.ActionDescriptor as ControllerActionDescriptor).ControllerTypeInfo.AsType(); + //方法信息 + var method = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo; + //方法参数 + var arguments = context.ActionArguments; + //开始计时 + var stopwatch = Stopwatch.StartNew(); + var auditInfo = new AuditInfo + { + UserInfo = "软绵绵", + ServiceName = type != null ? type.FullName: "", + MethodName = method.Name, + ////请求参数转Json + Parameters = JsonConvert.SerializeObject(arguments), + ExecutionTime = DateTime.Now, + BrowserInfo = context.HttpContext.Request.Headers["User-Agent"].ToString(), + ClientIpAddress = context.HttpContext.Connection.RemoteIpAddress.ToString(), + //ClientName = _clientInfoProvider.ComputerName.TruncateWithPostfix(EntityDefault.FieldsLength100), + // Id = Guid.NewGuid().ToString() + }; + + ActionExecutedContext result = null; + try + { + result = await next(); + if (result.Exception != null && !result.ExceptionHandled) + { + auditInfo.Exception = result.Exception.ToString(); + } + } + catch (Exception ex) + { + auditInfo.Exception = ex.ToString(); + throw; + } + finally + { + stopwatch.Stop(); + auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds); + + if (result != null) + { + switch (result.Result) + { + case ObjectResult objectResult: + auditInfo.ReturnValue = JsonConvert.SerializeObject(objectResult.Value); + break; + + case JsonResult jsonResult: + auditInfo.ReturnValue = JsonConvert.SerializeObject(jsonResult.Value); + break; + + case ContentResult contentResult: + auditInfo.ReturnValue = contentResult.Content; + break; + } + } + Console.WriteLine(auditInfo.ToString()); + //保存审计日志 + await _auditLogService.InsertAsync(auditInfo); + } + } + + /// + /// 是否需要记录审计 + /// + /// + /// + private bool ShouldSaveAudit(ActionExecutingContext context) + { + if (!(context.ActionDescriptor is ControllerActionDescriptor)) + return false; + var methodInfo = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo; + + if (methodInfo == null) + { + return false; + } + + if (!methodInfo.IsPublic) + { + return false; + } + + // if (methodInfo.GetCustomAttribute() != null) + // { + // return true; + // } + + // if (methodInfo.GetCustomAttribute() != null) + // { + // return false; + // } + + // var classType = methodInfo.DeclaringType; + // if (classType != null) + // { + // if (classType.GetTypeInfo().GetCustomAttribute() != null) + // { + // return true; + // } + + // if (classType.GetTypeInfo().GetCustomAttribute() != null) + // { + // return false; + // } + // } + return true; + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..aa0c943226b7afa1da2ea5598bcb8eb6f93dd206 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" @@ -0,0 +1,164 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210703160108_sayupdate")] + partial class sayupdate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210703160108_sayupdate.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210703160108_sayupdate.cs" new file mode 100644 index 0000000000000000000000000000000000000000..2dddc8f71164d99006af7d0ca1adea5545524d13 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210703160108_sayupdate.cs" @@ -0,0 +1,104 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace WebApi.Api.Migrations +{ + public partial class sayupdate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Roles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RoleName = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Roles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Username = table.Column(type: "nvarchar(max)", nullable: true), + Password = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "UserRoles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + RoleId = table.Column(type: "int", nullable: false), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRoles", x => x.Id); + table.ForeignKey( + name: "FK_UserRoles_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserRoles_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_RoleId", + table: "UserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_UserId", + table: "UserRoles", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserRoles"); + + migrationBuilder.DropTable( + name: "Roles"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..c677ef3b00d783b8987f65fca520cb45779348ba --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.Designer.cs" @@ -0,0 +1,230 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210708090027_addAuditLogInfo")] + partial class addAuditLogInfo + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.AuditInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("BrowserInfo") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientIpAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientName") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("CustomData") + .HasColumnType("nvarchar(max)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Exception") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionDuration") + .HasColumnType("int"); + + b.Property("ExecutionTime") + .HasColumnType("datetime2"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("MethodName") + .HasColumnType("nvarchar(max)"); + + b.Property("Parameters") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("ReturnValue") + .HasColumnType("nvarchar(max)"); + + b.Property("ServiceName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserInfo") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("AuditInfo"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.cs" new file mode 100644 index 0000000000000000000000000000000000000000..1cfb5967a3fd49f6e86c3ae0c4bb6088c0ee54d0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.cs" @@ -0,0 +1,47 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace WebApi.Api.Migrations +{ + public partial class addAuditLogInfo : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditInfo", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Parameters = table.Column(type: "nvarchar(max)", nullable: true), + BrowserInfo = table.Column(type: "nvarchar(max)", nullable: true), + ClientName = table.Column(type: "nvarchar(max)", nullable: true), + ClientIpAddress = table.Column(type: "nvarchar(max)", nullable: true), + ExecutionDuration = table.Column(type: "int", nullable: false), + ExecutionTime = table.Column(type: "datetime2", nullable: false), + ReturnValue = table.Column(type: "nvarchar(max)", nullable: true), + Exception = table.Column(type: "nvarchar(max)", nullable: true), + MethodName = table.Column(type: "nvarchar(max)", nullable: true), + ServiceName = table.Column(type: "nvarchar(max)", nullable: true), + UserInfo = table.Column(type: "nvarchar(max)", nullable: true), + CustomData = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditInfo", x => x.Id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditInfo"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5d35f0f983a17e0b8de90d6e39ab99f523b1868e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" @@ -0,0 +1,228 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + partial class ShowDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.AuditInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("BrowserInfo") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientIpAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientName") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("CustomData") + .HasColumnType("nvarchar(max)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Exception") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionDuration") + .HasColumnType("int"); + + b.Property("ExecutionTime") + .HasColumnType("datetime2"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("MethodName") + .HasColumnType("nvarchar(max)"); + + b.Property("Parameters") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("ReturnValue") + .HasColumnType("nvarchar(max)"); + + b.Property("ServiceName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserInfo") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("AuditInfo"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/ParamModel/NewUser.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/ParamModel/NewUser.cs" new file mode 100644 index 0000000000000000000000000000000000000000..25aadb60eced86fc35ec9c5d6c3109c7e6e66b5d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/ParamModel/NewUser.cs" @@ -0,0 +1,8 @@ +namespace WebApi.Api.ParamModel +{ + public class NewUser + { + public string Username { get; set; } + public string Password { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/ParamModel/TokenParameter.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/ParamModel/TokenParameter.cs" new file mode 100644 index 0000000000000000000000000000000000000000..7b2d8d7690ed580a9d16df951e132aa539742e02 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/ParamModel/TokenParameter.cs" @@ -0,0 +1,14 @@ +namespace WebApi.Api.ParamModel +{ + public class TokenParameter + { + //token的密钥,不能泄露,泄露意味着所有人都可以生成你的token并且访问你的服务或者接口 + public string Secret { get; set; } + //发行人(可以是个人或组织) + public string Issuer { get; set; } + //token的作用时间,单位为分钟,过期后需要重新获取 + public int AccessExpiration { get; set; } + //类似一个token的东西的作用时间,单位为分钟,用于重新获取token + public int RefreshExpiration { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..7d3cf1707ff490daadf63c1a4d12e31487edd1aa --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..77df5e56016c789b33766433eac6a0515672f692 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58834", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "WebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Repository/EfRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Repository/EfRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..843a2eef1a48d6e36c6827d60be019a1da712cd7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Repository/EfRepository.cs" @@ -0,0 +1,161 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; +using WebApi.Api.Db; + +namespace WebApi.Api.Repository +{ + public class EfRepository : IRepository where T : BaseEntity + { + /// + /// 数据库上下文的变量,此处是使用常规手段,直接初始化一个数据库上下文的实例对象 + /// + /// + private ShowDb _db; + + public EfRepository(ShowDb db) + { + _db=db; + } + + /// + /// 一个字段成员,用于内部Entity属性 + /// + private DbSet _entity; + + + /// + /// 一个访问受限的属性,只有访问器,总是返回一个代表T类型的表对象 + /// + /// + protected DbSet Entity + { + get + { + // 如果 _entity为空(没有指向一个对象),则从数据库上下文重新获得一个 + if (_entity == null) + { + _entity = _db.Set(); + } + return _entity; + } + } + + /// + /// 代表一个可以用于查询T类型的表 + /// + /// + public IQueryable Table + { + get + { + return Entity.AsQueryable(); + } + } + + + /// + /// 删除(指定T类型,在数据库当中代表指定的表)指定Id的记录 + /// + /// + public void Delete(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + Entity.Remove(t); + _db.SaveChanges(); + } + + public T GetById(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + return t; + } + + public void Insert(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + Entity.Add(entity); + _db.SaveChanges(); + } + + public async Task InsertAsync(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + await Entity.AddAsync(entity); + await _db.SaveChangesAsync(); + } + + public void InsertBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + Entity.AddRange(entities); + _db.SaveChanges(); + } + + public async Task InsertBulkAsync(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + await Entity.AddRangeAsync(entities); + await _db.SaveChangesAsync(); + } + + public void Update(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.UpdatedTime = DateTime.Now; + _db.SaveChanges(); + } + + public void UpdateBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.UpdatedTime = DateTime.Now; + } + + + _db.SaveChanges(); + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Repository/IRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Repository/IRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..8023d6ad5d35c15807ab73aec5adfc015b219893 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Repository/IRepository.cs" @@ -0,0 +1,65 @@ +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace WebApi.Api.Repository +{ + + public interface IRepository + { + IQueryable Table { get; } + + /// + /// 根据Id获取指定实体 + /// + /// + /// + T GetById(int id); + + /// + /// 使用实体对象,插入数据 + /// + /// 需要插入的对象 + void Insert(T entity); + + /// + /// 使用实体对象,插入数据(异步) + /// + /// 需要插入的对象 + /// + Task InsertAsync(T entity); + + /// + /// 批量插入若干数据 + /// + /// 待插入的若干实体数据 + void InsertBulk(IEnumerable entities); + + /// + /// 批量插入若干数据(异步) + /// + /// 待插入的若干实体数据 + /// + Task InsertBulkAsync(IEnumerable entities); + + /// + /// 根据对象更新数据 + /// + /// 要更新的对象 + void Update(T entity); + + + /// + /// 根据对象更新数据(异步) + /// + /// 要更新的若干个实体 + /// + void UpdateBulk(IEnumerable entities); + + /// + /// 根据Id删除对应的记录 + /// + /// 主键id + void Delete(int id); + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..bb2b96e38241c6a0d8ca2df3c21503992bcc8b64 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Startup.cs" @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Repository; +using WebApi.Api.Fliters; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using System.Text; +using WebApi.Api.ParamModel; + +namespace WebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddDbContext(o => o.UseSqlServer()); + //注册对数据库的基本操作服务到容器 + services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); + //注册验证器(使用什么配置来验证token) + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option => + { + //是否要求使用https + option.RequireHttpsMetadata = false; + //是否要保存token + option.SaveToken = true; + //使用配置中间件,获得token配置 + var token = Configuration.GetSection("tokenParameter").Get(); + //验证器核心属性 + option.TokenValidationParameters = new TokenValidationParameters + { + //是否要验证生成token的秘钥 + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(token.Secret)), + //是否要验证发行token的组织或者个人 + ValidateIssuer = true, + ValidIssuer = token.Issuer, + //是否验证受众 + ValidateAudience = false, + }; + }); + + services.AddControllers(options => + { + options.Filters.Add(typeof(AuditLogActionFilter)); + }); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + // 将token的验证注册到中间件 + app.UseAuthentication(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Utils/TokenHelper.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Utils/TokenHelper.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5497a4f220858779b34444b681cf4299c0fe270e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/Utils/TokenHelper.cs" @@ -0,0 +1,30 @@ +using System; +using System.Text; +using Microsoft.IdentityModel.Tokens; +using System.Security.Claims; +using System.IdentityModel.Tokens.Jwt; +using WebApi.Api.Entity; +using WebApi.Api.ParamModel; + +namespace WebApi.Api.Utils +{ + public class TokenHelper + { + public static string GenerateToekn(TokenParameter tokenParameter,Users user) + { + var claims = new[] + { + new Claim(ClaimTypes.Name, user.Username), + new Claim(ClaimTypes.Role, "admin"), + }; + + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)); + var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + var jwtToken = new JwtSecurityToken(tokenParameter.Issuer, null, claims, expires: DateTime.UtcNow.AddMinutes(tokenParameter.AccessExpiration), signingCredentials: credentials); + + var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); + + return token; + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..f3b286243716f48478a95af985f6aeb254bdf124 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/WebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/WebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..bf59a6b33505acf1370cc86be131663c843ea12e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/WebApi.Api.csproj" @@ -0,0 +1,18 @@ + + + + netcoreapp3.1 + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..b6c148490851d8525f42d6d8aa2ff7dc9f14b3f1 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.Api/appsettings.json" @@ -0,0 +1,16 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*", + "TokenParameter": { + "secret": "123456123456123456", + "issuer": "Wooz", + "accessExpiration": 120, + "refreshExpiration": 1440 + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.sln" new file mode 100644 index 0000000000000000000000000000000000000000..cca47b63d3b41649047761af0f258004d9bd759c --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/WebApi.sln" @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi.Api", "WebApi.Api\WebApi.Api.csproj", "{F3409974-472B-4C81-AECF-CAA46F86D5BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..afc533ef567597697078ac58fa871237c922e32a --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/api.http" @@ -0,0 +1,39 @@ +###Get 获取用户列表 +GET http://localhost:5000/users HTTP/1.1 +# Authorization: Bearer +Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1pbiIsImV4cCI6MTYyNTgwMjY1MCwiaXNzIjoiV29veiJ9.jMwfRUcgdRA1C7pnZzNXOZiSUy8JMDR6atq0SN8Xp4U + +### 获取指定id用户 +GET http://localhost:5000/users/2 HTTP/1.1 +# Authorization: Bearer +Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1pbiIsImV4cCI6MTYyNTgwMjY1MCwiaXNzIjoiV29veiJ9.jMwfRUcgdRA1C7pnZzNXOZiSUy8JMDR6atq0SN8Xp4U + +### Post 创建用户 +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "Username":"admin", + "Password":"1234" +} + +### Put 修改指定用户 +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "Username":"good nice + 土笨笨", + "Password":"111" +} + +### Delete 删除指定用户 +DELETE http://localhost:5000/users/2 HTTP/1.1 + +### 登录并获取token +POST http://localhost:5000/users/token HTTP/1.1 +Content-Type: application/json + +{ + "username":"admin", + "password":"1234" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/readme.md" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/readme.md" new file mode 100644 index 0000000000000000000000000000000000000000..60df8e30a8ea2048f8174d806d13bbb7aec8ab7a --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-JWT-\345\256\241\350\256\241\346\227\245\345\277\227-\345\256\214\346\225\264/readme.md" @@ -0,0 +1,55 @@ +# WebApi 项目 + +## 工具 Visual Studio Code (vs code) +```sh +基于`asp.net core`和`netcoreapp3.1`, + +下载路径:https://docs.microsoft.com/zh-cn/dotnet/core/sdk +``` + +### 1. 使用Restfull约定,来分别完成数据的CRUD,类似如下用法: + + | 路由形式 | 说明 | + | - | -| + | get /users | 获取用户列表 | + | get /users/:id | 获取指定id的用户 | + | post /users | 增加用户 | + | put /users/:id | 修改指定用户 | + | delete /users/:id | 删除指定用户 | + +### 2. VSCode 的应用 及 各种(在当前开发环境下)插件(C#、C# Extension、C# XML Document 、Rest Client)的使用 + +### 3. dotnet命令的各种应用 (如:文件名为 WebApi ) +```sh +dotnet new sln -n WebApi + +cd WebApi + ++ # 创建项目 WebApi.Api +dotnet new webapi -n WebApi.Api + +dotnet sln add WebApi.Api + +cd WebApi.Api + +dotnet add package Microsoft.EntityFrameworkCore + +dotnet add package Microsoft.EntityFrameworkCore.SqlServer + +(定义实体类型、数据库上下文,定义数据连接字符串) + +dotnet tool install --global dotnet-ef + +dotnet add package Microsoft.EntityFrameworkCore.Design + +dotnet ef migrations add XXXX + +dotnet ef database update +``` + +## 还原项目 +```sh ++ # 克隆项目下来先还原项目 + +dotnet restore +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..2e2ea077e2a073d40997f799f703b358b68cb6c0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,176 @@ +using System; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using WebApi.Api.Entity; +using System.Linq; +using Newtonsoft.Json; +using WebApi.Api.ParamModel; +using WebApi.Api.Repository; +using WebApi.Api.Utils; +using Microsoft.Extensions.Configuration; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase + { + private IRepository _usersRespository; + private TokenParameter _tokenParameter; + private readonly IConfiguration _configuration; + public UsersController(IConfiguration configuration, IRepository usersRespository) + { + _configuration = configuration; + _usersRespository = usersRespository; + _tokenParameter = _configuration.GetSection("TokenParameter").Get(); + } + + [HttpGet] + public dynamic Get() + { + var users = _usersRespository.Table.ToList(); + return new + { + Code = 1020, + Data = users, + Msg = "获取用户列表成功" + }; + } + + [HttpGet("{id}")] + public dynamic Get(int id) + { + var user = _usersRespository.GetById(id); + return user; + } + + [HttpPost] + public string Post(NewUser model) + { + JsonSerializerSettings settings = new JsonSerializerSettings(); + + settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + var user = new Users + { + Username = model.Username, + Password = model.Password + }; + + _usersRespository.Insert(user); + + var res = new + { + Code = 1000, + Data = user, + Msg = "创建用户成功" + }; + return JsonConvert.SerializeObject(res, settings); + } + + [HttpPut("{id}")] + public dynamic Put(int id, NewUser model) + { + var user = _usersRespository.GetById(id); + + if (user != null) + { + user.Username = model.Username; + user.Password = model.Password; + user.UpdatedTime = DateTime.Now; + _usersRespository.Update(user); + return new + { + Code = 1000, + Data = user, + Msg = string.Format("你修改的用户的id为:{0},已经修改成功,请注意查收", id) + }; + } + else + { + return new + { + Code = 104, + Data = "", + Msg = "指定Id的用户不存在,请确认后重试" + }; + } + } + + [HttpDelete("{id}")] + public dynamic Delete(int id) + { + var user = _usersRespository.GetById(id); + if (user != null) + { + _usersRespository.Delete(id); + return new + { + Code = 1000, + Msg = string.Format("删除指定id为{0}的用户成功", id) + }; + } + else + { + return new + { + Code = 1000, + Data = "", + Msg = "指定id的用户不存在,请确认重试" + }; + } + } + + private IEnumerable GetUsers() + { + var users = new List{ + new Users{ + Id=1, + Username="你好", + Password="确实好啊" + }, + new Users{ + Id=2, + Username="真的吗", + Password="不啊" + }, + new Users{ + Id=3, + Username="可以吗", + Password="我觉得不行" + }, + }; + return users; + } + + [HttpPost, Route("token")] + public dynamic GetToken(NewUser model) + { + var username = model.Username.Trim(); + var password = model.Password.Trim(); + + var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault(); + + if (user == null) + { + return new + { + Code = 1001, + Data = user, + Msg = "用户名或密码不正确,请核对后重试" + }; + } + + var token = TokenHelper.GenerateToekn(_tokenParameter, user); + var refreshToken = "123456"; + + var res = new + { + Code = 1000, + Data = new { Token = token, RefreshToken = refreshToken }, + Msg = "用户登录成功,获取token成功" + }; + return res; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d2b595033ea0a3f002f879ebe5ecf13ac4c01152 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Data/ShowDb.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Data/ShowDb.cs" new file mode 100644 index 0000000000000000000000000000000000000000..932f2f90faf6ff05869f94750cc0851f7ffd2eeb --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Data/ShowDb.cs" @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; + +namespace WebApi.Api.Db +{ + public class ShowDb : DbContext + { + // 因为我们使用AddDbContext到容器,所以此处必须得有带参数的构造函数 + public ShowDb(DbContextOptions options) : base(options) + { + + } + + public DbSet Users { get; set; } + public DbSet Roles { get; set; } + public DbSet UserRoles { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(@"server=.;database=ShowDb;uid=sa;pwd=123456;"); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/BaseEntity.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/BaseEntity.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5816e54e01de59ac6335eeeb903dc7c0b54deec0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/BaseEntity.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api.Entity +{ + public abstract class BaseEntity + { + public int Id { get; set; } + public bool IsActived { get; set; } + public bool IsDeleted { get; set; } + public DateTime CreatedTime { get; set; } + public DateTime UpdatedTime { get; set; } + public int DisplayOrder { get; set; } + public string Remarks { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/Roles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/Roles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..0f178913d9786955db8ff83f9507e0538e0a657d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/Roles.cs" @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Roles : BaseEntity + { + public string RoleName { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/UserRoles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/UserRoles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..67be0a855feb6fffd2604dfc58613a4749669629 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/UserRoles.cs" @@ -0,0 +1,12 @@ +using System; + +namespace WebApi.Api.Entity +{ + public class UserRoles : BaseEntity + { + public int UserId { get; set; } + public int RoleId { get; set; } + public virtual Users User { get; set; } + public virtual Roles Role { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..96b6787fa69f7876ea4b37d6e038fa7ea9b83ef9 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Entity/Users.cs" @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Users : BaseEntity + { + public string Username { get; set; } + public string Password { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..aa0c943226b7afa1da2ea5598bcb8eb6f93dd206 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" @@ -0,0 +1,164 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210703160108_sayupdate")] + partial class sayupdate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/20210703160108_sayupdate.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/20210703160108_sayupdate.cs" new file mode 100644 index 0000000000000000000000000000000000000000..2dddc8f71164d99006af7d0ca1adea5545524d13 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/20210703160108_sayupdate.cs" @@ -0,0 +1,104 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace WebApi.Api.Migrations +{ + public partial class sayupdate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Roles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RoleName = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Roles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Username = table.Column(type: "nvarchar(max)", nullable: true), + Password = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "UserRoles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + RoleId = table.Column(type: "int", nullable: false), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRoles", x => x.Id); + table.ForeignKey( + name: "FK_UserRoles_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserRoles_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_RoleId", + table: "UserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_UserId", + table: "UserRoles", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserRoles"); + + migrationBuilder.DropTable( + name: "Roles"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" new file mode 100644 index 0000000000000000000000000000000000000000..13535a338e07b1a0a73564610bebfbef80af7e41 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" @@ -0,0 +1,162 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + partial class ShowDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/ParamModel/NewUser.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/ParamModel/NewUser.cs" new file mode 100644 index 0000000000000000000000000000000000000000..25aadb60eced86fc35ec9c5d6c3109c7e6e66b5d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/ParamModel/NewUser.cs" @@ -0,0 +1,8 @@ +namespace WebApi.Api.ParamModel +{ + public class NewUser + { + public string Username { get; set; } + public string Password { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/ParamModel/TokenParameter.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/ParamModel/TokenParameter.cs" new file mode 100644 index 0000000000000000000000000000000000000000..e09e0b99b01f2a253068f9f690e517ef7c8d6eb4 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/ParamModel/TokenParameter.cs" @@ -0,0 +1,10 @@ +namespace WebApi.Api.ParamModel +{ + public class TokenParameter + { + public string Secret { get; set; } + public string Issuer { get; set; } + public int AccessExpiration { get; set; } + public int RefreshExpiration { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..7d3cf1707ff490daadf63c1a4d12e31487edd1aa --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..77df5e56016c789b33766433eac6a0515672f692 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58834", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "WebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Repository/EfRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Repository/EfRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..843a2eef1a48d6e36c6827d60be019a1da712cd7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Repository/EfRepository.cs" @@ -0,0 +1,161 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; +using WebApi.Api.Db; + +namespace WebApi.Api.Repository +{ + public class EfRepository : IRepository where T : BaseEntity + { + /// + /// 数据库上下文的变量,此处是使用常规手段,直接初始化一个数据库上下文的实例对象 + /// + /// + private ShowDb _db; + + public EfRepository(ShowDb db) + { + _db=db; + } + + /// + /// 一个字段成员,用于内部Entity属性 + /// + private DbSet _entity; + + + /// + /// 一个访问受限的属性,只有访问器,总是返回一个代表T类型的表对象 + /// + /// + protected DbSet Entity + { + get + { + // 如果 _entity为空(没有指向一个对象),则从数据库上下文重新获得一个 + if (_entity == null) + { + _entity = _db.Set(); + } + return _entity; + } + } + + /// + /// 代表一个可以用于查询T类型的表 + /// + /// + public IQueryable Table + { + get + { + return Entity.AsQueryable(); + } + } + + + /// + /// 删除(指定T类型,在数据库当中代表指定的表)指定Id的记录 + /// + /// + public void Delete(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + Entity.Remove(t); + _db.SaveChanges(); + } + + public T GetById(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + return t; + } + + public void Insert(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + Entity.Add(entity); + _db.SaveChanges(); + } + + public async Task InsertAsync(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + await Entity.AddAsync(entity); + await _db.SaveChangesAsync(); + } + + public void InsertBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + Entity.AddRange(entities); + _db.SaveChanges(); + } + + public async Task InsertBulkAsync(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + await Entity.AddRangeAsync(entities); + await _db.SaveChangesAsync(); + } + + public void Update(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.UpdatedTime = DateTime.Now; + _db.SaveChanges(); + } + + public void UpdateBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.UpdatedTime = DateTime.Now; + } + + + _db.SaveChanges(); + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Repository/IRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Repository/IRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..8023d6ad5d35c15807ab73aec5adfc015b219893 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Repository/IRepository.cs" @@ -0,0 +1,65 @@ +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace WebApi.Api.Repository +{ + + public interface IRepository + { + IQueryable Table { get; } + + /// + /// 根据Id获取指定实体 + /// + /// + /// + T GetById(int id); + + /// + /// 使用实体对象,插入数据 + /// + /// 需要插入的对象 + void Insert(T entity); + + /// + /// 使用实体对象,插入数据(异步) + /// + /// 需要插入的对象 + /// + Task InsertAsync(T entity); + + /// + /// 批量插入若干数据 + /// + /// 待插入的若干实体数据 + void InsertBulk(IEnumerable entities); + + /// + /// 批量插入若干数据(异步) + /// + /// 待插入的若干实体数据 + /// + Task InsertBulkAsync(IEnumerable entities); + + /// + /// 根据对象更新数据 + /// + /// 要更新的对象 + void Update(T entity); + + + /// + /// 根据对象更新数据(异步) + /// + /// 要更新的若干个实体 + /// + void UpdateBulk(IEnumerable entities); + + /// + /// 根据Id删除对应的记录 + /// + /// 主键id + void Delete(int id); + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..9ba374fbfab7c984bb87f018a9b7b93d15944c03 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Startup.cs" @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Repository; + +namespace WebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddDbContext(o =>o.UseSqlServer()); + //注册对数据库的基本操作服务到容器 + services.AddScoped(typeof(IRepository<>),typeof(EfRepository<>)); + + services.AddControllers(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Utils/TokenHelper.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Utils/TokenHelper.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5497a4f220858779b34444b681cf4299c0fe270e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/Utils/TokenHelper.cs" @@ -0,0 +1,30 @@ +using System; +using System.Text; +using Microsoft.IdentityModel.Tokens; +using System.Security.Claims; +using System.IdentityModel.Tokens.Jwt; +using WebApi.Api.Entity; +using WebApi.Api.ParamModel; + +namespace WebApi.Api.Utils +{ + public class TokenHelper + { + public static string GenerateToekn(TokenParameter tokenParameter,Users user) + { + var claims = new[] + { + new Claim(ClaimTypes.Name, user.Username), + new Claim(ClaimTypes.Role, "admin"), + }; + + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)); + var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + var jwtToken = new JwtSecurityToken(tokenParameter.Issuer, null, claims, expires: DateTime.UtcNow.AddMinutes(tokenParameter.AccessExpiration), signingCredentials: credentials); + + var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); + + return token; + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..f3b286243716f48478a95af985f6aeb254bdf124 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/WebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/WebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..bf59a6b33505acf1370cc86be131663c843ea12e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/WebApi.Api.csproj" @@ -0,0 +1,18 @@ + + + + netcoreapp3.1 + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..b6c148490851d8525f42d6d8aa2ff7dc9f14b3f1 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.Api/appsettings.json" @@ -0,0 +1,16 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*", + "TokenParameter": { + "secret": "123456123456123456", + "issuer": "Wooz", + "accessExpiration": 120, + "refreshExpiration": 1440 + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.sln" new file mode 100644 index 0000000000000000000000000000000000000000..cca47b63d3b41649047761af0f258004d9bd759c --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/WebApi.sln" @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi.Api", "WebApi.Api\WebApi.Api.csproj", "{F3409974-472B-4C81-AECF-CAA46F86D5BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..d2742055e3cccd8ce30412effdb62f58ef5c5523 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/api.http" @@ -0,0 +1,36 @@ +###Get 获取 +GET http://localhost:5000/users HTTP/1.1 + +### +GET http://localhost:5000/users/2 HTTP/1.1 + + +### Post 创建用户 +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "Username":"admin", + "Password":"123" +} + +### Put 修改指定用户 +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "Username":"good nice + 土笨笨", + "Password":"阿萨德股份" +} + +### Delete 删除 +DELETE http://localhost:5000/users/2 HTTP/1.1 + +### 登录并获取token +POST http://localhost:5000/users/token HTTP/1.1 +Content-Type: application/json + +{ + "username":"admin", + "password":"123" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/readme.md" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/readme.md" new file mode 100644 index 0000000000000000000000000000000000000000..78f49d4cd4736b62332fe237ded5891f42e60c6e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-Jwt/readme.md" @@ -0,0 +1,51 @@ +# WebApi 项目 + +## 工具 Visual Studio Code (vs code) + +1. 基于`asp.net core`和`netcoreapp3.1`, + +下载路径:https://docs.microsoft.com/zh-cn/dotnet/core/sdk + +### 1. 使用Restfull约定,来分别完成数据的CRUD,类似如下用法: + + | 路由形式 | 说明 | + | - | -| + | get /users | 获取用户列表 | + | get /users/:id | 获取指定id的用户 | + | post /users | 增加用户 | + | put /users/:id | 修改指定用户 | + | delete /users/:id | 删除指定用户 | + +### 2. VSCode 的应用 及 各种(在当前开发环境下)插件(C#、C# Extension、C# XML Document 、Rest Client)的使用 + +### 3. dotnet命令的各种应用 +``` +dotnet new sln -n Admin3000.Backend + +cd Admin3000.Backend + +dotnet new webapi -n Admin3000.Backend.Api + +dotnet sln add Admin3000.Backend.Api + +cd Admin3000.Backend.Api + +dotnet add package Microsoft.EntityFrameworkCore + +dotnet add package Microsoft.EntityFrameworkCore.SqlServer + +(定义实体类型、数据库上下文,定义数据连接字符串) + +dotnet tool install --global dotnet-ef + +dotnet add package Microsoft.EntityFrameworkCore.Design + +dotnet ef migrations add XXXX + +dotnet ef database update +``` + +# 还原项目 +``` +dotnet restore +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..2e2ea077e2a073d40997f799f703b358b68cb6c0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,176 @@ +using System; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using WebApi.Api.Entity; +using System.Linq; +using Newtonsoft.Json; +using WebApi.Api.ParamModel; +using WebApi.Api.Repository; +using WebApi.Api.Utils; +using Microsoft.Extensions.Configuration; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase + { + private IRepository _usersRespository; + private TokenParameter _tokenParameter; + private readonly IConfiguration _configuration; + public UsersController(IConfiguration configuration, IRepository usersRespository) + { + _configuration = configuration; + _usersRespository = usersRespository; + _tokenParameter = _configuration.GetSection("TokenParameter").Get(); + } + + [HttpGet] + public dynamic Get() + { + var users = _usersRespository.Table.ToList(); + return new + { + Code = 1020, + Data = users, + Msg = "获取用户列表成功" + }; + } + + [HttpGet("{id}")] + public dynamic Get(int id) + { + var user = _usersRespository.GetById(id); + return user; + } + + [HttpPost] + public string Post(NewUser model) + { + JsonSerializerSettings settings = new JsonSerializerSettings(); + + settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + var user = new Users + { + Username = model.Username, + Password = model.Password + }; + + _usersRespository.Insert(user); + + var res = new + { + Code = 1000, + Data = user, + Msg = "创建用户成功" + }; + return JsonConvert.SerializeObject(res, settings); + } + + [HttpPut("{id}")] + public dynamic Put(int id, NewUser model) + { + var user = _usersRespository.GetById(id); + + if (user != null) + { + user.Username = model.Username; + user.Password = model.Password; + user.UpdatedTime = DateTime.Now; + _usersRespository.Update(user); + return new + { + Code = 1000, + Data = user, + Msg = string.Format("你修改的用户的id为:{0},已经修改成功,请注意查收", id) + }; + } + else + { + return new + { + Code = 104, + Data = "", + Msg = "指定Id的用户不存在,请确认后重试" + }; + } + } + + [HttpDelete("{id}")] + public dynamic Delete(int id) + { + var user = _usersRespository.GetById(id); + if (user != null) + { + _usersRespository.Delete(id); + return new + { + Code = 1000, + Msg = string.Format("删除指定id为{0}的用户成功", id) + }; + } + else + { + return new + { + Code = 1000, + Data = "", + Msg = "指定id的用户不存在,请确认重试" + }; + } + } + + private IEnumerable GetUsers() + { + var users = new List{ + new Users{ + Id=1, + Username="你好", + Password="确实好啊" + }, + new Users{ + Id=2, + Username="真的吗", + Password="不啊" + }, + new Users{ + Id=3, + Username="可以吗", + Password="我觉得不行" + }, + }; + return users; + } + + [HttpPost, Route("token")] + public dynamic GetToken(NewUser model) + { + var username = model.Username.Trim(); + var password = model.Password.Trim(); + + var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault(); + + if (user == null) + { + return new + { + Code = 1001, + Data = user, + Msg = "用户名或密码不正确,请核对后重试" + }; + } + + var token = TokenHelper.GenerateToekn(_tokenParameter, user); + var refreshToken = "123456"; + + var res = new + { + Code = 1000, + Data = new { Token = token, RefreshToken = refreshToken }, + Msg = "用户登录成功,获取token成功" + }; + return res; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d2b595033ea0a3f002f879ebe5ecf13ac4c01152 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Data/ShowDb.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Data/ShowDb.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5e6a9d25c5e6092601e61f0784ecd9df781b41ed --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Data/ShowDb.cs" @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; + +namespace WebApi.Api.Db +{ + public class ShowDb : DbContext + { + // 因为我们使用AddDbContext到容器,所以此处必须得有带参数的构造函数 + public ShowDb(DbContextOptions options) : base(options) + { + + } + + public DbSet Users { get; set; } + public DbSet Roles { get; set; } + public DbSet UserRoles { get; set; } + public DbSet AuditInfo { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(@"server=.;database=ShowDb;uid=sa;pwd=123456;"); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/AuditInfo.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/AuditInfo.cs" new file mode 100644 index 0000000000000000000000000000000000000000..74e81c343060138d8c0fab7601ce00becef42b49 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/AuditInfo.cs" @@ -0,0 +1,56 @@ +using System; + +namespace WebApi.Api.Entity +{ + public class AuditInfo : BaseEntity + { + /// + /// 调用参数 + /// + public string Parameters { get; set; } + /// + /// 浏览器信息 + /// + public string BrowserInfo { get; set; } + /// + /// 客户端信息 + /// + public string ClientName { get; set; } + /// + /// 客户端IP地址 + /// + public string ClientIpAddress { get; set; } + /// + /// 执行耗时 + /// + public int ExecutionDuration { get; set; } + /// + /// 执行时间 + /// + public DateTime ExecutionTime { get; set; } + /// + /// 返回内容 + /// + public string ReturnValue { get; set; } + /// + /// 异常对象 + /// + public string Exception { get; set; } + /// + /// 方法名 + /// + public string MethodName { get; set; } + /// + /// 服务名 + /// + public string ServiceName { get; set; } + /// + /// 调用者信息 + /// + public string UserInfo { get; set; } + /// + /// 自定义数据 + /// + public string CustomData { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/BaseEntity.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/BaseEntity.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5816e54e01de59ac6335eeeb903dc7c0b54deec0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/BaseEntity.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api.Entity +{ + public abstract class BaseEntity + { + public int Id { get; set; } + public bool IsActived { get; set; } + public bool IsDeleted { get; set; } + public DateTime CreatedTime { get; set; } + public DateTime UpdatedTime { get; set; } + public int DisplayOrder { get; set; } + public string Remarks { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/Roles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/Roles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..0f178913d9786955db8ff83f9507e0538e0a657d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/Roles.cs" @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Roles : BaseEntity + { + public string RoleName { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/UserRoles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/UserRoles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..67be0a855feb6fffd2604dfc58613a4749669629 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/UserRoles.cs" @@ -0,0 +1,12 @@ +using System; + +namespace WebApi.Api.Entity +{ + public class UserRoles : BaseEntity + { + public int UserId { get; set; } + public int RoleId { get; set; } + public virtual Users User { get; set; } + public virtual Roles Role { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..96b6787fa69f7876ea4b37d6e038fa7ea9b83ef9 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Entity/Users.cs" @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Users : BaseEntity + { + public string Username { get; set; } + public string Password { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Filters/AuditLogActionFilter.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Filters/AuditLogActionFilter.cs" new file mode 100644 index 0000000000000000000000000000000000000000..f172f9aa1b86308ad09691e4742d29ea31d4d74e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Filters/AuditLogActionFilter.cs" @@ -0,0 +1,148 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using WebApi.Api.Entity; +using WebApi.Api.Repository; + +namespace WebApi.Api.Fliters +{ + public class AuditLogActionFilter : IAsyncActionFilter + { + private readonly IRepository _auditLogService; + + public AuditLogActionFilter( + IRepository auditLogService + ) + { + _auditLogService = auditLogService; + } + + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + // 判断是否写日志 + if (!ShouldSaveAudit(context)) + { + await next(); + return; + } + //接口Type + var type = (context.ActionDescriptor as ControllerActionDescriptor).ControllerTypeInfo.AsType(); + //方法信息 + var method = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo; + //方法参数 + var arguments = context.ActionArguments; + //开始计时 + var stopwatch = Stopwatch.StartNew(); + var auditInfo = new AuditInfo + { + UserInfo = "软绵绵", + ServiceName = type != null ? type.FullName: "", + MethodName = method.Name, + ////请求参数转Json + Parameters = JsonConvert.SerializeObject(arguments), + ExecutionTime = DateTime.Now, + BrowserInfo = context.HttpContext.Request.Headers["User-Agent"].ToString(), + ClientIpAddress = context.HttpContext.Connection.RemoteIpAddress.ToString(), + //ClientName = _clientInfoProvider.ComputerName.TruncateWithPostfix(EntityDefault.FieldsLength100), + // Id = Guid.NewGuid().ToString() + }; + + ActionExecutedContext result = null; + try + { + result = await next(); + if (result.Exception != null && !result.ExceptionHandled) + { + auditInfo.Exception = result.Exception.ToString(); + } + } + catch (Exception ex) + { + auditInfo.Exception = ex.ToString(); + throw; + } + finally + { + stopwatch.Stop(); + auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds); + + if (result != null) + { + switch (result.Result) + { + case ObjectResult objectResult: + auditInfo.ReturnValue = JsonConvert.SerializeObject(objectResult.Value); + break; + + case JsonResult jsonResult: + auditInfo.ReturnValue = JsonConvert.SerializeObject(jsonResult.Value); + break; + + case ContentResult contentResult: + auditInfo.ReturnValue = contentResult.Content; + break; + } + } + Console.WriteLine(auditInfo.ToString()); + //保存审计日志 + await _auditLogService.InsertAsync(auditInfo); + } + } + + /// + /// 是否需要记录审计 + /// + /// + /// + private bool ShouldSaveAudit(ActionExecutingContext context) + { + if (!(context.ActionDescriptor is ControllerActionDescriptor)) + return false; + var methodInfo = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo; + + if (methodInfo == null) + { + return false; + } + + if (!methodInfo.IsPublic) + { + return false; + } + + // if (methodInfo.GetCustomAttribute() != null) + // { + // return true; + // } + + // if (methodInfo.GetCustomAttribute() != null) + // { + // return false; + // } + + // var classType = methodInfo.DeclaringType; + // if (classType != null) + // { + // if (classType.GetTypeInfo().GetCustomAttribute() != null) + // { + // return true; + // } + + // if (classType.GetTypeInfo().GetCustomAttribute() != null) + // { + // return false; + // } + // } + return true; + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..aa0c943226b7afa1da2ea5598bcb8eb6f93dd206 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" @@ -0,0 +1,164 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210703160108_sayupdate")] + partial class sayupdate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210703160108_sayupdate.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210703160108_sayupdate.cs" new file mode 100644 index 0000000000000000000000000000000000000000..2dddc8f71164d99006af7d0ca1adea5545524d13 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210703160108_sayupdate.cs" @@ -0,0 +1,104 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace WebApi.Api.Migrations +{ + public partial class sayupdate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Roles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RoleName = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Roles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Username = table.Column(type: "nvarchar(max)", nullable: true), + Password = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "UserRoles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + RoleId = table.Column(type: "int", nullable: false), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRoles", x => x.Id); + table.ForeignKey( + name: "FK_UserRoles_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserRoles_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_RoleId", + table: "UserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_UserId", + table: "UserRoles", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserRoles"); + + migrationBuilder.DropTable( + name: "Roles"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..c677ef3b00d783b8987f65fca520cb45779348ba --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.Designer.cs" @@ -0,0 +1,230 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210708090027_addAuditLogInfo")] + partial class addAuditLogInfo + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.AuditInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("BrowserInfo") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientIpAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientName") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("CustomData") + .HasColumnType("nvarchar(max)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Exception") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionDuration") + .HasColumnType("int"); + + b.Property("ExecutionTime") + .HasColumnType("datetime2"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("MethodName") + .HasColumnType("nvarchar(max)"); + + b.Property("Parameters") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("ReturnValue") + .HasColumnType("nvarchar(max)"); + + b.Property("ServiceName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserInfo") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("AuditInfo"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.cs" new file mode 100644 index 0000000000000000000000000000000000000000..1cfb5967a3fd49f6e86c3ae0c4bb6088c0ee54d0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/20210708090027_addAuditLogInfo.cs" @@ -0,0 +1,47 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace WebApi.Api.Migrations +{ + public partial class addAuditLogInfo : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditInfo", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Parameters = table.Column(type: "nvarchar(max)", nullable: true), + BrowserInfo = table.Column(type: "nvarchar(max)", nullable: true), + ClientName = table.Column(type: "nvarchar(max)", nullable: true), + ClientIpAddress = table.Column(type: "nvarchar(max)", nullable: true), + ExecutionDuration = table.Column(type: "int", nullable: false), + ExecutionTime = table.Column(type: "datetime2", nullable: false), + ReturnValue = table.Column(type: "nvarchar(max)", nullable: true), + Exception = table.Column(type: "nvarchar(max)", nullable: true), + MethodName = table.Column(type: "nvarchar(max)", nullable: true), + ServiceName = table.Column(type: "nvarchar(max)", nullable: true), + UserInfo = table.Column(type: "nvarchar(max)", nullable: true), + CustomData = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditInfo", x => x.Id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditInfo"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5d35f0f983a17e0b8de90d6e39ab99f523b1868e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" @@ -0,0 +1,228 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + partial class ShowDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.AuditInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("BrowserInfo") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientIpAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientName") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("CustomData") + .HasColumnType("nvarchar(max)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Exception") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionDuration") + .HasColumnType("int"); + + b.Property("ExecutionTime") + .HasColumnType("datetime2"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("MethodName") + .HasColumnType("nvarchar(max)"); + + b.Property("Parameters") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("ReturnValue") + .HasColumnType("nvarchar(max)"); + + b.Property("ServiceName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserInfo") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("AuditInfo"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/ParamModel/NewUser.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/ParamModel/NewUser.cs" new file mode 100644 index 0000000000000000000000000000000000000000..25aadb60eced86fc35ec9c5d6c3109c7e6e66b5d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/ParamModel/NewUser.cs" @@ -0,0 +1,8 @@ +namespace WebApi.Api.ParamModel +{ + public class NewUser + { + public string Username { get; set; } + public string Password { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/ParamModel/TokenParameter.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/ParamModel/TokenParameter.cs" new file mode 100644 index 0000000000000000000000000000000000000000..e09e0b99b01f2a253068f9f690e517ef7c8d6eb4 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/ParamModel/TokenParameter.cs" @@ -0,0 +1,10 @@ +namespace WebApi.Api.ParamModel +{ + public class TokenParameter + { + public string Secret { get; set; } + public string Issuer { get; set; } + public int AccessExpiration { get; set; } + public int RefreshExpiration { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..7d3cf1707ff490daadf63c1a4d12e31487edd1aa --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..77df5e56016c789b33766433eac6a0515672f692 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58834", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "WebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Repository/EfRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Repository/EfRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..843a2eef1a48d6e36c6827d60be019a1da712cd7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Repository/EfRepository.cs" @@ -0,0 +1,161 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; +using WebApi.Api.Db; + +namespace WebApi.Api.Repository +{ + public class EfRepository : IRepository where T : BaseEntity + { + /// + /// 数据库上下文的变量,此处是使用常规手段,直接初始化一个数据库上下文的实例对象 + /// + /// + private ShowDb _db; + + public EfRepository(ShowDb db) + { + _db=db; + } + + /// + /// 一个字段成员,用于内部Entity属性 + /// + private DbSet _entity; + + + /// + /// 一个访问受限的属性,只有访问器,总是返回一个代表T类型的表对象 + /// + /// + protected DbSet Entity + { + get + { + // 如果 _entity为空(没有指向一个对象),则从数据库上下文重新获得一个 + if (_entity == null) + { + _entity = _db.Set(); + } + return _entity; + } + } + + /// + /// 代表一个可以用于查询T类型的表 + /// + /// + public IQueryable Table + { + get + { + return Entity.AsQueryable(); + } + } + + + /// + /// 删除(指定T类型,在数据库当中代表指定的表)指定Id的记录 + /// + /// + public void Delete(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + Entity.Remove(t); + _db.SaveChanges(); + } + + public T GetById(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + return t; + } + + public void Insert(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + Entity.Add(entity); + _db.SaveChanges(); + } + + public async Task InsertAsync(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + await Entity.AddAsync(entity); + await _db.SaveChangesAsync(); + } + + public void InsertBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + Entity.AddRange(entities); + _db.SaveChanges(); + } + + public async Task InsertBulkAsync(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + await Entity.AddRangeAsync(entities); + await _db.SaveChangesAsync(); + } + + public void Update(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.UpdatedTime = DateTime.Now; + _db.SaveChanges(); + } + + public void UpdateBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.UpdatedTime = DateTime.Now; + } + + + _db.SaveChanges(); + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Repository/IRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Repository/IRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..8023d6ad5d35c15807ab73aec5adfc015b219893 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Repository/IRepository.cs" @@ -0,0 +1,65 @@ +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace WebApi.Api.Repository +{ + + public interface IRepository + { + IQueryable Table { get; } + + /// + /// 根据Id获取指定实体 + /// + /// + /// + T GetById(int id); + + /// + /// 使用实体对象,插入数据 + /// + /// 需要插入的对象 + void Insert(T entity); + + /// + /// 使用实体对象,插入数据(异步) + /// + /// 需要插入的对象 + /// + Task InsertAsync(T entity); + + /// + /// 批量插入若干数据 + /// + /// 待插入的若干实体数据 + void InsertBulk(IEnumerable entities); + + /// + /// 批量插入若干数据(异步) + /// + /// 待插入的若干实体数据 + /// + Task InsertBulkAsync(IEnumerable entities); + + /// + /// 根据对象更新数据 + /// + /// 要更新的对象 + void Update(T entity); + + + /// + /// 根据对象更新数据(异步) + /// + /// 要更新的若干个实体 + /// + void UpdateBulk(IEnumerable entities); + + /// + /// 根据Id删除对应的记录 + /// + /// 主键id + void Delete(int id); + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..4c90fe3f0f522257cb053379c5206a3caa3ab337 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Startup.cs" @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Repository; +using WebApi.Api.Fliters; + +namespace WebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddDbContext(o =>o.UseSqlServer()); + //注册对数据库的基本操作服务到容器 + services.AddScoped(typeof(IRepository<>),typeof(EfRepository<>)); + + services.AddControllers(options=>{ + options.Filters.Add(typeof(AuditLogActionFilter)); + }); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Utils/TokenHelper.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Utils/TokenHelper.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5497a4f220858779b34444b681cf4299c0fe270e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/Utils/TokenHelper.cs" @@ -0,0 +1,30 @@ +using System; +using System.Text; +using Microsoft.IdentityModel.Tokens; +using System.Security.Claims; +using System.IdentityModel.Tokens.Jwt; +using WebApi.Api.Entity; +using WebApi.Api.ParamModel; + +namespace WebApi.Api.Utils +{ + public class TokenHelper + { + public static string GenerateToekn(TokenParameter tokenParameter,Users user) + { + var claims = new[] + { + new Claim(ClaimTypes.Name, user.Username), + new Claim(ClaimTypes.Role, "admin"), + }; + + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)); + var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + var jwtToken = new JwtSecurityToken(tokenParameter.Issuer, null, claims, expires: DateTime.UtcNow.AddMinutes(tokenParameter.AccessExpiration), signingCredentials: credentials); + + var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); + + return token; + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..f3b286243716f48478a95af985f6aeb254bdf124 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/WebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/WebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..bf59a6b33505acf1370cc86be131663c843ea12e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/WebApi.Api.csproj" @@ -0,0 +1,18 @@ + + + + netcoreapp3.1 + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..b6c148490851d8525f42d6d8aa2ff7dc9f14b3f1 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.Api/appsettings.json" @@ -0,0 +1,16 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*", + "TokenParameter": { + "secret": "123456123456123456", + "issuer": "Wooz", + "accessExpiration": 120, + "refreshExpiration": 1440 + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.sln" new file mode 100644 index 0000000000000000000000000000000000000000..cca47b63d3b41649047761af0f258004d9bd759c --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/WebApi.sln" @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi.Api", "WebApi.Api\WebApi.Api.csproj", "{F3409974-472B-4C81-AECF-CAA46F86D5BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..b39b9d2fe7371cd220f00eb1448fcac1b4bf0a25 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/api.http" @@ -0,0 +1,36 @@ +###Get 获取 +GET http://localhost:5000/users HTTP/1.1 +Authorization: Breaer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1pbiIsImV4cCI6MTYyNTc2MzEyOCwiaXNzIjoiV29veiJ9.ViheRjt9m_gUjd33RIvLSYFdyH9qNpHXyR6QTHSkJyQ +### +GET http://localhost:5000/users/2 HTTP/1.1 +Authorization: Breaer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1pbiIsImV4cCI6MTYyNTc2MzEyOCwiaXNzIjoiV29veiJ9.ViheRjt9m_gUjd33RIvLSYFdyH9qNpHXyR6QTHSkJyQ + +### Post 创建用户 +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "Username":"admin", + "Password":"1234" +} + +### Put 修改指定用户 +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "Username":"good nice + 土笨笨", + "Password":"111" +} + +### Delete 删除 +DELETE http://localhost:5000/users/2 HTTP/1.1 + +### 登录并获取token +POST http://localhost:5000/users/token HTTP/1.1 +Content-Type: application/json + +{ + "username":"admin", + "password":"1234" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/readme.md" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/readme.md" new file mode 100644 index 0000000000000000000000000000000000000000..78f49d4cd4736b62332fe237ded5891f42e60c6e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi-\345\256\241\350\256\241\346\227\245\345\277\227/readme.md" @@ -0,0 +1,51 @@ +# WebApi 项目 + +## 工具 Visual Studio Code (vs code) + +1. 基于`asp.net core`和`netcoreapp3.1`, + +下载路径:https://docs.microsoft.com/zh-cn/dotnet/core/sdk + +### 1. 使用Restfull约定,来分别完成数据的CRUD,类似如下用法: + + | 路由形式 | 说明 | + | - | -| + | get /users | 获取用户列表 | + | get /users/:id | 获取指定id的用户 | + | post /users | 增加用户 | + | put /users/:id | 修改指定用户 | + | delete /users/:id | 删除指定用户 | + +### 2. VSCode 的应用 及 各种(在当前开发环境下)插件(C#、C# Extension、C# XML Document 、Rest Client)的使用 + +### 3. dotnet命令的各种应用 +``` +dotnet new sln -n Admin3000.Backend + +cd Admin3000.Backend + +dotnet new webapi -n Admin3000.Backend.Api + +dotnet sln add Admin3000.Backend.Api + +cd Admin3000.Backend.Api + +dotnet add package Microsoft.EntityFrameworkCore + +dotnet add package Microsoft.EntityFrameworkCore.SqlServer + +(定义实体类型、数据库上下文,定义数据连接字符串) + +dotnet tool install --global dotnet-ef + +dotnet add package Microsoft.EntityFrameworkCore.Design + +dotnet ef migrations add XXXX + +dotnet ef database update +``` + +# 还原项目 +``` +dotnet restore +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Controllers/UsersController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Controllers/UsersController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..1db27a97691a1077f10da90437e4affd0c954380 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Controllers/UsersController.cs" @@ -0,0 +1,141 @@ +using System; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using WebApi.Api.Entity; +using System.Linq; +using Newtonsoft.Json; +using WebApi.Api.ParamModel; +using WebApi.Api.Repository; + +namespace MyWebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsersController : ControllerBase + { + private IRepository _usersRespository; + + public UsersController(IRepository usersRespository) + { + _usersRespository = usersRespository; + } + + [HttpGet] + public dynamic Get() + { + var users = _usersRespository.Table.ToList(); + return new + { + Code = 1020, + Data = users, + Msg = "获取用户列表成功" + }; + } + + [HttpGet("{id}")] + public dynamic Get(int id) + { + var user = _usersRespository.GetById(id); + return user; + } + + [HttpPost] + public string Post(NewUser model) + { + JsonSerializerSettings settings = new JsonSerializerSettings(); + + settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + var user = new Users + { + Username = model.Username, + Password = model.Password + }; + + _usersRespository.Insert(user); + + var res = new + { + Code = 1000, + Data = user, + Msg = "创建用户成功" + }; + return JsonConvert.SerializeObject(res, settings); + } + + [HttpPut("{id}")] + public dynamic Put(int id, NewUser model) + { + var user = _usersRespository.GetById(id); + + if (user != null) + { + user.Username = model.Username; + user.Password = model.Password; + user.UpdatedTime = DateTime.Now; + _usersRespository.Update(user); + return new + { + Code = 1000, + Data = user, + Msg = string.Format("你修改的用户的id为:{0},已经修改成功,请注意查收", id) + }; + } + else + { + return new + { + Code = 104, + Data = "", + Msg = "指定Id的用户不存在,请确认后重试" + }; + } + } + + [HttpDelete("{id}")] + public dynamic Delete(int id) + { + var user = _usersRespository.GetById(id); + if (user != null) + { + _usersRespository.Delete(id); + return new + { + Code = 1000, + Msg = string.Format("删除指定id为{0}的用户成功", id) + }; + } + else + { + return new + { + Code = 1000, + Data = "", + Msg = "指定id的用户不存在,请确认重试" + }; + } + } + + private IEnumerable GetUsers() + { + var users = new List{ + new Users{ + Id=1, + Username="你好", + Password="确实好啊" + }, + new Users{ + Id=2, + Username="真的吗", + Password="不啊" + }, + new Users{ + Id=3, + Username="可以吗", + Password="我觉得不行" + }, + }; + return users; + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Controllers/WeatherForecastController.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Controllers/WeatherForecastController.cs" new file mode 100644 index 0000000000000000000000000000000000000000..d2b595033ea0a3f002f879ebe5ecf13ac4c01152 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Controllers/WeatherForecastController.cs" @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { + var rng = new Random(); + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Data/ShowDb.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Data/ShowDb.cs" new file mode 100644 index 0000000000000000000000000000000000000000..932f2f90faf6ff05869f94750cc0851f7ffd2eeb --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Data/ShowDb.cs" @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; + +namespace WebApi.Api.Db +{ + public class ShowDb : DbContext + { + // 因为我们使用AddDbContext到容器,所以此处必须得有带参数的构造函数 + public ShowDb(DbContextOptions options) : base(options) + { + + } + + public DbSet Users { get; set; } + public DbSet Roles { get; set; } + public DbSet UserRoles { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(@"server=.;database=ShowDb;uid=sa;pwd=123456;"); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/BaseEntity.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/BaseEntity.cs" new file mode 100644 index 0000000000000000000000000000000000000000..5816e54e01de59ac6335eeeb903dc7c0b54deec0 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/BaseEntity.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api.Entity +{ + public abstract class BaseEntity + { + public int Id { get; set; } + public bool IsActived { get; set; } + public bool IsDeleted { get; set; } + public DateTime CreatedTime { get; set; } + public DateTime UpdatedTime { get; set; } + public int DisplayOrder { get; set; } + public string Remarks { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/Roles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/Roles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..0f178913d9786955db8ff83f9507e0538e0a657d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/Roles.cs" @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Roles : BaseEntity + { + public string RoleName { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/UserRoles.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/UserRoles.cs" new file mode 100644 index 0000000000000000000000000000000000000000..67be0a855feb6fffd2604dfc58613a4749669629 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/UserRoles.cs" @@ -0,0 +1,12 @@ +using System; + +namespace WebApi.Api.Entity +{ + public class UserRoles : BaseEntity + { + public int UserId { get; set; } + public int RoleId { get; set; } + public virtual Users User { get; set; } + public virtual Roles Role { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/Users.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/Users.cs" new file mode 100644 index 0000000000000000000000000000000000000000..cbb873c0f7fcb457399c95819bff0202390502cc --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Entity/Users.cs" @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace WebApi.Api.Entity +{ + public class Users : BaseEntity + { + public string Username { get; set; } + public String Password { get; set; } + public virtual IEnumerable UserRoles { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" new file mode 100644 index 0000000000000000000000000000000000000000..aa0c943226b7afa1da2ea5598bcb8eb6f93dd206 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/20210703160108_sayupdate.Designer.cs" @@ -0,0 +1,164 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + [Migration("20210703160108_sayupdate")] + partial class sayupdate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/20210703160108_sayupdate.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/20210703160108_sayupdate.cs" new file mode 100644 index 0000000000000000000000000000000000000000..2dddc8f71164d99006af7d0ca1adea5545524d13 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/20210703160108_sayupdate.cs" @@ -0,0 +1,104 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace WebApi.Api.Migrations +{ + public partial class sayupdate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Roles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RoleName = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Roles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Username = table.Column(type: "nvarchar(max)", nullable: true), + Password = table.Column(type: "nvarchar(max)", nullable: true), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "UserRoles", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + RoleId = table.Column(type: "int", nullable: false), + IsActived = table.Column(type: "bit", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedTime = table.Column(type: "datetime2", nullable: false), + UpdatedTime = table.Column(type: "datetime2", nullable: false), + DisplayOrder = table.Column(type: "int", nullable: false), + Remarks = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRoles", x => x.Id); + table.ForeignKey( + name: "FK_UserRoles_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserRoles_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_RoleId", + table: "UserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_UserId", + table: "UserRoles", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserRoles"); + + migrationBuilder.DropTable( + name: "Roles"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" new file mode 100644 index 0000000000000000000000000000000000000000..13535a338e07b1a0a73564610bebfbef80af7e41 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Migrations/ShowDbModelSnapshot.cs" @@ -0,0 +1,162 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using WebApi.Api.Db; + +namespace WebApi.Api.Migrations +{ + [DbContext(typeof(ShowDb))] + partial class ShowDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.7") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + b.Property("CreatedTime") + .HasColumnType("datetime2"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("IsActived") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Password") + .HasColumnType("nvarchar(max)"); + + b.Property("Remarks") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedTime") + .HasColumnType("datetime2"); + + b.Property("Username") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.UserRoles", b => + { + b.HasOne("WebApi.Api.Entity.Roles", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("WebApi.Api.Entity.Users", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Roles", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("WebApi.Api.Entity.Users", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/ParamModel/NewUser.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/ParamModel/NewUser.cs" new file mode 100644 index 0000000000000000000000000000000000000000..25aadb60eced86fc35ec9c5d6c3109c7e6e66b5d --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/ParamModel/NewUser.cs" @@ -0,0 +1,8 @@ +namespace WebApi.Api.ParamModel +{ + public class NewUser + { + public string Username { get; set; } + public string Password { get; set; } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Program.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Program.cs" new file mode 100644 index 0000000000000000000000000000000000000000..7d3cf1707ff490daadf63c1a4d12e31487edd1aa --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Program.cs" @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace WebApi.Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Properties/launchSettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Properties/launchSettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..77df5e56016c789b33766433eac6a0515672f692 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Properties/launchSettings.json" @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58834", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "WebApi.Api": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Repository/EfRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Repository/EfRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..843a2eef1a48d6e36c6827d60be019a1da712cd7 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Repository/EfRepository.cs" @@ -0,0 +1,161 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Entity; +using WebApi.Api.Db; + +namespace WebApi.Api.Repository +{ + public class EfRepository : IRepository where T : BaseEntity + { + /// + /// 数据库上下文的变量,此处是使用常规手段,直接初始化一个数据库上下文的实例对象 + /// + /// + private ShowDb _db; + + public EfRepository(ShowDb db) + { + _db=db; + } + + /// + /// 一个字段成员,用于内部Entity属性 + /// + private DbSet _entity; + + + /// + /// 一个访问受限的属性,只有访问器,总是返回一个代表T类型的表对象 + /// + /// + protected DbSet Entity + { + get + { + // 如果 _entity为空(没有指向一个对象),则从数据库上下文重新获得一个 + if (_entity == null) + { + _entity = _db.Set(); + } + return _entity; + } + } + + /// + /// 代表一个可以用于查询T类型的表 + /// + /// + public IQueryable Table + { + get + { + return Entity.AsQueryable(); + } + } + + + /// + /// 删除(指定T类型,在数据库当中代表指定的表)指定Id的记录 + /// + /// + public void Delete(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + Entity.Remove(t); + _db.SaveChanges(); + } + + public T GetById(int id) + { + var t = Entity.Where(x => x.Id == id).FirstOrDefault(); + return t; + } + + public void Insert(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + Entity.Add(entity); + _db.SaveChanges(); + } + + public async Task InsertAsync(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + + await Entity.AddAsync(entity); + await _db.SaveChangesAsync(); + } + + public void InsertBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + Entity.AddRange(entities); + _db.SaveChanges(); + } + + public async Task InsertBulkAsync(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.IsActived = true; + entity.IsDeleted = false; + entity.CreatedTime = DateTime.Now; + entity.UpdatedTime = DateTime.Now; + entity.DisplayOrder = 0; + } + await Entity.AddRangeAsync(entities); + await _db.SaveChangesAsync(); + } + + public void Update(T entity) + { + if (entity == null) + { + throw new System.NullReferenceException(); + } + + entity.UpdatedTime = DateTime.Now; + _db.SaveChanges(); + } + + public void UpdateBulk(IEnumerable entities) + { + foreach (var entity in entities) + { + entity.UpdatedTime = DateTime.Now; + } + + + _db.SaveChanges(); + } + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Repository/IRepository.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Repository/IRepository.cs" new file mode 100644 index 0000000000000000000000000000000000000000..8023d6ad5d35c15807ab73aec5adfc015b219893 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Repository/IRepository.cs" @@ -0,0 +1,65 @@ +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace WebApi.Api.Repository +{ + + public interface IRepository + { + IQueryable Table { get; } + + /// + /// 根据Id获取指定实体 + /// + /// + /// + T GetById(int id); + + /// + /// 使用实体对象,插入数据 + /// + /// 需要插入的对象 + void Insert(T entity); + + /// + /// 使用实体对象,插入数据(异步) + /// + /// 需要插入的对象 + /// + Task InsertAsync(T entity); + + /// + /// 批量插入若干数据 + /// + /// 待插入的若干实体数据 + void InsertBulk(IEnumerable entities); + + /// + /// 批量插入若干数据(异步) + /// + /// 待插入的若干实体数据 + /// + Task InsertBulkAsync(IEnumerable entities); + + /// + /// 根据对象更新数据 + /// + /// 要更新的对象 + void Update(T entity); + + + /// + /// 根据对象更新数据(异步) + /// + /// 要更新的若干个实体 + /// + void UpdateBulk(IEnumerable entities); + + /// + /// 根据Id删除对应的记录 + /// + /// 主键id + void Delete(int id); + } +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Startup.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Startup.cs" new file mode 100644 index 0000000000000000000000000000000000000000..9ba374fbfab7c984bb87f018a9b7b93d15944c03 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/Startup.cs" @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; +using WebApi.Api.Repository; + +namespace WebApi.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + 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.AddDbContext(o =>o.UseSqlServer()); + //注册对数据库的基本操作服务到容器 + services.AddScoped(typeof(IRepository<>),typeof(EfRepository<>)); + + services.AddControllers(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/WeatherForecast.cs" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/WeatherForecast.cs" new file mode 100644 index 0000000000000000000000000000000000000000..f3b286243716f48478a95af985f6aeb254bdf124 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/WeatherForecast.cs" @@ -0,0 +1,15 @@ +using System; + +namespace WebApi.Api +{ + public class WeatherForecast + { + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/WebApi.Api.csproj" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/WebApi.Api.csproj" new file mode 100644 index 0000000000000000000000000000000000000000..5de34d82c182e8d8b67652c3676eee939d6d24cd --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/WebApi.Api.csproj" @@ -0,0 +1,17 @@ + + + + netcoreapp3.1 + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/appsettings.Development.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/appsettings.Development.json" new file mode 100644 index 0000000000000000000000000000000000000000..8983e0fc1c5e2795ccfde0c771c6d66c88ef4a42 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/appsettings.Development.json" @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/appsettings.json" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/appsettings.json" new file mode 100644 index 0000000000000000000000000000000000000000..d9d9a9bff6fd6f3ee7ea00de958f135a4a28c6e6 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.Api/appsettings.json" @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.sln" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.sln" new file mode 100644 index 0000000000000000000000000000000000000000..cca47b63d3b41649047761af0f258004d9bd759c --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/WebApi.sln" @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi.Api", "WebApi.Api\WebApi.Api.csproj", "{F3409974-472B-4C81-AECF-CAA46F86D5BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x64.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.ActiveCfg = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Debug|x86.Build.0 = Debug|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|Any CPU.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x64.Build.0 = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.ActiveCfg = Release|Any CPU + {F3409974-472B-4C81-AECF-CAA46F86D5BB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/api.http" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/api.http" new file mode 100644 index 0000000000000000000000000000000000000000..83d9d12a0d7a7d1b74b8f5a119ab352932a3fc56 --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/api.http" @@ -0,0 +1,34 @@ +###Get 获取 + +GET http://localhost:5000/users HTTP/1.1 + +### +GET http://localhost:5000/users/2 HTTP/1.1 + + +### Post 添加 +POST http://localhost:5000/users HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"good nice + 土笨笨", + "PassWord":"123" +} + +### Put 修改 +PUT http://localhost:5000/users/1 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"这里", + "PassWord":"123" +} + +### Delete 删除 +DELETE http://localhost:5000/users/2 HTTP/1.1 +Content-Type: application/json + +{ + "UserName":"哪里", + "PassWord":"123" +} \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/readme.md" "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/readme.md" new file mode 100644 index 0000000000000000000000000000000000000000..78f49d4cd4736b62332fe237ded5891f42e60c6e --- /dev/null +++ "b/\346\242\201\350\211\272\347\274\244/MyApi/WebApi/readme.md" @@ -0,0 +1,51 @@ +# WebApi 项目 + +## 工具 Visual Studio Code (vs code) + +1. 基于`asp.net core`和`netcoreapp3.1`, + +下载路径:https://docs.microsoft.com/zh-cn/dotnet/core/sdk + +### 1. 使用Restfull约定,来分别完成数据的CRUD,类似如下用法: + + | 路由形式 | 说明 | + | - | -| + | get /users | 获取用户列表 | + | get /users/:id | 获取指定id的用户 | + | post /users | 增加用户 | + | put /users/:id | 修改指定用户 | + | delete /users/:id | 删除指定用户 | + +### 2. VSCode 的应用 及 各种(在当前开发环境下)插件(C#、C# Extension、C# XML Document 、Rest Client)的使用 + +### 3. dotnet命令的各种应用 +``` +dotnet new sln -n Admin3000.Backend + +cd Admin3000.Backend + +dotnet new webapi -n Admin3000.Backend.Api + +dotnet sln add Admin3000.Backend.Api + +cd Admin3000.Backend.Api + +dotnet add package Microsoft.EntityFrameworkCore + +dotnet add package Microsoft.EntityFrameworkCore.SqlServer + +(定义实体类型、数据库上下文,定义数据连接字符串) + +dotnet tool install --global dotnet-ef + +dotnet add package Microsoft.EntityFrameworkCore.Design + +dotnet ef migrations add XXXX + +dotnet ef database update +``` + +# 还原项目 +``` +dotnet restore +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.25.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.25\357\274\210Vue \345\243\260\346\230\216\345\274\217\346\270\262\346\237\223\357\274\211.md" similarity index 83% rename from "\346\242\201\350\211\272\347\274\244/Vue - 2021.05.25.md" rename to "\346\242\201\350\211\272\347\274\244/Vue - 2021.05.25\357\274\210Vue \345\243\260\346\230\216\345\274\217\346\270\262\346\237\223\357\274\211.md" index 4446d74c527df940a134fc0d188d26964bdb279d..3200964711304f3931c60bfce862d85ef39b4d1e 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.25.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.25\357\274\210Vue \345\243\260\346\230\216\345\274\217\346\270\262\346\237\223\357\274\211.md" @@ -1,13 +1,14 @@ -## Vue.js 第一节课 +# Vue.js 第一节课 -+ Vue 类似于View 构建用户界面的渐进式框架 +## 声明式渲染 +```sh -+ Vue可以自底想上逐层应用,Vue 的核心库只关注视图层 ++ # Vue 类似于View 构建用户界面的渐进式框架 -## 声明式渲染 ++ # Vue可以自底想上逐层应用,Vue 的核心库只关注视图层 -``` -
+ # 代码块 +

{{site}}

{{url}}

{{alexa}}

@@ -33,6 +34,7 @@ ``` +```sh + 这意味着我们接下来的改动全部在以上指定的 div 内,div 外部不受影响。 + 接下来我们看看如何定义数据对象。 @@ -42,11 +44,13 @@ + methods 用于定义的函数,可以通过 return 来返回函数值。 + {{ }} 用于输出对象属性和函数返回值。 +``` 结果:---------------- ![](./node/2021-05-25_104756.png) -``` +```sh + #代码块

@@ -75,16 +79,17 @@ console.log(top); -``` -``` -鼠标停几秒呀,查看此处动态绑定的信息 -``` +## 鼠标停几秒呀,查看此处动态绑定的信息 -注意:v-bind attribute 被称为指令,指令带有前缀 v-,以表示它们是 Vue 提供的特殊 attribute。 +# 注意:v-bind attribute 被称为指令,指令带有前缀 v-,以表示它们是 Vue 提供的特殊 attribute。 -## 条件与循环 ``` -
+ +## 条件与循环 +```sh + #代码块 + +
  1. {{ todo.text }} diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.26.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.26\357\274\210Vue \346\235\241\344\273\266\345\276\252\347\216\257\357\274\211.md" similarity index 70% rename from "\346\242\201\350\211\272\347\274\244/Vue - 2021.05.26.md" rename to "\346\242\201\350\211\272\347\274\244/Vue - 2021.05.26\357\274\210Vue \346\235\241\344\273\266\345\276\252\347\216\257\357\274\211.md" index 428c1370ffd5ba2b590028e4c4abcea7afd79275..725993c502d18eff2f145e937999b041c360fdf8 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.26.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.26\357\274\210Vue \346\235\241\344\273\266\345\276\252\347\216\257\357\274\211.md" @@ -1,14 +1,16 @@ -## Vue.js 第二节课 +# Vue.js 第二节课 ## 条件循环 +```sh -+ 循环使用 v-for 指令。 ++ # 循环使用 v-for 指令。 -+ v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组并且 site 是数组元素迭代的别名。 ++ # v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组并且 site 是数组元素迭代的别名。 -+ v-for 可以绑定数据到数组来渲染一个列表: ++ # v-for 可以绑定数据到数组来渲染一个列表: -``` + + # 代码块
    • {{item.taskName}}
    • @@ -49,27 +51,33 @@ ``` ## 处理用户输入 +```sh -+ v-on 指令添加一个事件监听器 ++ # v-on 指令添加一个事件监听器 -+ v-model 指令,它能轻松实现表单输入和应用状态之间的双向绑定 -``` -
      - - - - - - - - - -
      -
      - -``` ++ # v-model 指令,它能轻松实现表单输入和应用状态之间的双向绑定 + + # 代码块 +
      + + + + + + + + + +
      +
      + + ``` - -``` -1. beforeUpdate 视图渲染之前,此时数据还是久的,data的数据的最新的 - - + 数据更新时调用,发生在虚拟 DOM 打补丁之前。这里适合在更新之前访问现有的 DOM,比如手动移除已添加的事件监听器。 - -2. updated 视图渲染之后,数据是最新的 - - + 由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。 - -+ 在$data发生变化后,才开始调用beforeUpdate是我理解了的,但是在beforeUpdate钩子函数中输出的$el和updated钩子函数中输出的$el是不一样的 - -+ 最初 mounted 是 '湖人',第一个在 beforeUpdate 中给 mounted 赋值时,比如赋值成 'world',会触发更新。 -第二次进入 beforeUpdate 时,mounted 又被赋值成 'world',但是这个值与之前的 'world' 相等, -这时就不会触发更新了,而数组每次重新赋值后都是创建了一个新对象,会重新更新。 ``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.29.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.29\357\274\210Vue \346\250\241\346\235\277\350\257\255\346\263\225\357\274\211.md" similarity index 78% rename from "\346\242\201\350\211\272\347\274\244/Vue - 2021.05.29.md" rename to "\346\242\201\350\211\272\347\274\244/Vue - 2021.05.29\357\274\210Vue \346\250\241\346\235\277\350\257\255\346\263\225\357\274\211.md" index f233e7d22553da0e579907431b6c7b9392ac886b..d0232367632355a0aa75212a0f5040a47ad7f92c 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.29.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.05.29\357\274\210Vue \346\250\241\346\235\277\350\257\255\346\263\225\357\274\211.md" @@ -1,21 +1,26 @@ -## Vue.js 第四节课 (Vue 模板语法) 原代码Vue见 -+ v-on:事件名 -``` +# Vue.js 第四节课 (Vue 模板语法) 原代码Vue见 + +```sh ++ # v-on:事件名 + -``` -+ 点击之后,Vue会运行add() -``` + ++ # 点击之后,Vue会运行add() + -``` -+ 点击事件之后,Vue会运行xxx(1) -``` + ++ # 点击事件之后,Vue会运行xxx(1) + -``` -+ 点击之后,Vue会运行msg+=1,函数就加括号调用,否则就直接运行代码 + ++ # 点击之后,Vue会运行msg+=1,函数就加括号调用,否则就直接运行代码 ``` + +```sh +# 代码块 + -
      @@ -47,4 +52,5 @@ } }) + ``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.01.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.01\357\274\210Vue Class \344\270\216 Style \347\273\221\345\256\232\357\274\211.md" similarity index 55% rename from "\346\242\201\350\211\272\347\274\244/Vue - 2021.06.01.md" rename to "\346\242\201\350\211\272\347\274\244/Vue - 2021.06.01\357\274\210Vue Class \344\270\216 Style \347\273\221\345\256\232\357\274\211.md" index edfbaca4daa53531ce0b732dcb753cad13ff1ede..5a4e1ba5412e991e998e0d5dc21b5c5940876eb8 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.01.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.01\357\274\210Vue Class \344\270\216 Style \347\273\221\345\256\232\357\274\211.md" @@ -1,16 +1,19 @@ -## Vue.js 第五节课 (Vue Class 与 Style 绑定) +# Vue.js 第五节课 (Vue Class 与 Style 绑定) -### 一、Class 与 Style -+ https://www.cnblogs.com/feiyu159/p/8673092.html +## 一、Class 与 Style +```sh ++ # https://www.cnblogs.com/feiyu159/p/8673092.html -+ 在将 v-bind 用于 class 和 style 时,表达式结果的类型是字符串、对象或数组。 ++ # 在将 v-bind 用于 class 和 style 时,表达式结果的类型是字符串、对象或数组。 -+ Vue 对标签 style 属性进行了优化,可以支持 对象、字符串、数组形式的赋值 ++ # Vue 对标签 style 属性进行了优化,可以支持 对象、字符串、数组形式的赋值 +``` +## 二、对象语法 +```sh +## v-bind:class 指令也可以与普通的 class attribute 共存。当有如下模板: -### 二、对象语法 -+ v-bind:class 指令也可以与普通的 class attribute 共存。当有如下模板: -``` + # 代码块
      反倒是
      @@ -33,9 +36,10 @@ } }) -``` -+ 直接绑定到一个样式对象通常更好,这会让模板更清晰:对象语法常结合返回对象的计算属性使用。 -``` + +## 直接绑定到一个样式对象通常更好,这会让模板更清晰:对象语法常结合返回对象的计算属性使用。 + + # 代码块
      丰东股份
      @@ -52,47 +56,51 @@ } }) + +## 当 isActive 或者 hasError 变化时,class 列表将相应地更新 ``` -+ 当 isActive 或者 hasError 变化时,class 列表将相应地更新 -### 2.1 绑定字面量对象 +## 2.1 绑定字面量对象 +```sh + 改变 div 的背景色,给 div 绑定到 class: active + 结果为:通过修改 isActive 的值来决定是否添加样式:.active -``` + + # 代码块(style) -``` -``` - -
      -
      -

      {{message}}

      + + # 代码块(body) + +
      +
      +

      {{message}}

      +
      -
      - + - - + data: { + message: 'hello vue !', + isActive: true, + } + }) + + ``` ### 三、数组语法 -``` +```sh + # 代码块
      迷之微笑
      -``` -``` + 结果:models值为true全部显示 ok值为false不显示 -``` -``` + 结果:models值为true显示 梗 值为false显示 这是一个梗 -``` -2. v-show +====================================================== +### 2. v-show +====================================================== + 注意,v-show 不支持 //template// 元素,也不支持 v-else。 + 当模板属性为true的时候控制台显示为display:block。属性值为false的时候控制台显示display: none -``` -
      + # 代码块 + +
      • {{item.red}}
      @@ -65,9 +68,11 @@ }) ``` -+ 有条件地跳过循环的执行,那么可以将 v-if 置于外层元素+ +## 有条件地跳过循环的执行,那么可以将 v-if 置于外层元素+ + +```sh + # 代码块 -```
      • {{item.red}}
      • @@ -86,21 +91,26 @@ }) - lisa为false时全部不显示,Lisa为true时全部显示 -``` + ## lisa为false时全部不显示,Lisa为true时全部显示 - ### 注意:v-if 与 v-for 一起使用 + +# 注意:v-if 与 v-for 一起使用 1. 永远不要把 v-if 和 v-for 同时用在同一个元素上。 2. 当 Vue 处理指令时,v-for 比 v-if 具有更高的优先级 +``` - ### 列表渲染 + ## 列表渲染 + ```sh + v-for 指令需要使用 item in items 形式的特殊语法,其中 items 是源数据数组,而 item 则是被迭代的数组元素的别名。 + v-for 支持一个可选的第二个参数 - ``` + + + # 代码块 +
        • @@ -119,20 +129,26 @@ ] } }) - ``` +``` + +## 维护状态 -### 维护状态 +```sh + 使用 v-for 渲染的元素列表时,它默认使用“就地更新”的策略 -### 在组件上使用 v-for +## 在组件上使用 v-for + 任何数据都不会被自动传递到组件里,因为组件有自己独立的作用域。 + 在
            元素内只有
          • 元素会被看作有效内容 -1. 方法一 -``` +============================================================================================================ +#### 方法一 +============================================================================================================ + + # 代码块 +
            @@ -179,10 +195,13 @@ } }) -``` -2. 方法二 -``` +============================================================================================================ +#### 方法二 +============================================================================================================ + + # 代码块 +
            diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.04.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.04\357\274\210Vue \344\272\213\344\273\266\345\244\204\347\220\206\357\274\211.md" similarity index 77% rename from "\346\242\201\350\211\272\347\274\244/Vue - 2021.06.04.md" rename to "\346\242\201\350\211\272\347\274\244/Vue - 2021.06.04\357\274\210Vue \344\272\213\344\273\266\345\244\204\347\220\206\357\274\211.md" index 238e9aea4037d72bda0e69c27b201c7eaa94ded0..5846cf75f1296085d47d3944c5f267847286edc0 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.04.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.04\357\274\210Vue \344\272\213\344\273\266\345\244\204\347\220\206\357\274\211.md" @@ -1,11 +1,52 @@ -## Vue.js 第五节课 (事件处理) - -### 事件处理 +# Vue.js 第五节课 (事件处理) +## 事件处理 +```sh + 可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码。 + v-on 可以接收一个定义的方法来调用。 ``` + +### 事件修饰符 +```sh +# 1. event.stopPropagation()方法 + +阻止事件的冒泡方法 + +# 2. event.preventDefault()方法 + +阻止默认事件的方法,连接不会被打开,但是会发生冒泡,冒泡会传递到上一层的父元素; + +# 3. return false ; + +这个方法比较暴力,会同时阻止事件冒泡和阻止默认事件;连接不会被打开,事件也不会传递到上一层的父元素;可以理解为return false就等于同时调用了'event.stopPropagation()'和'event.preventDefault()' + + +# 代码块 + + + + + +
            + + + + + +
            + + + +
            ...
            + + + +
            ...
            +``` + +## 代码块 +```sh
            @@ -43,41 +84,4 @@ }) // example2.greet() -``` - -### 事件修饰符 - -1. event.stopPropagation()方法 - -+ 阻止事件的冒泡方法 - -2. event.preventDefault()方法 - -+ 阻止默认事件的方法,连接不会被打开,但是会发生冒泡,冒泡会传递到上一层的父元素; - -3. return false ; - -+ 这个方法比较暴力,会同时阻止事件冒泡和阻止默认事件;连接不会被打开,事件也不会传递到上一层的父元 -素;可以理解为return false就等于同时调用了event.stopPropagation()和event.preventDefault() - -``` - - - - -
            - - - - - -
            - - - -
            ...
            - - - -
            ...
            ``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.05.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.05 \357\274\210Vue \350\241\250\345\215\225\350\276\223\345\205\245\347\273\221\345\256\232\357\274\211.md" similarity index 75% rename from "\346\242\201\350\211\272\347\274\244/Vue - 2021.06.05.md" rename to "\346\242\201\350\211\272\347\274\244/Vue - 2021.06.05 \357\274\210Vue \350\241\250\345\215\225\350\276\223\345\205\245\347\273\221\345\256\232\357\274\211.md" index 7c086ebb661395979d03c3fbc9fe5a3215bf6b48..196a5a01d0219a4950aa326f5f0eb31bc355ac38 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.05.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.05 \357\274\210Vue \350\241\250\345\215\225\350\276\223\345\205\245\347\273\221\345\256\232\357\274\211.md" @@ -1,22 +1,25 @@ -## Vue.js 第五节课 (表单输入绑定) - -### 表单输入绑定 +# Vue.js 第五节课 (表单输入绑定) +## 表单输入绑定 +```sh #### v-model指令   -+ 用 v-model 指令在表单 input、textarea 及 select 元素上创建双向数据绑定。 + 用 v-model 指令在表单 input、textarea 及 select 元素上创建双向数据绑定。 + v-model 会忽略所有表单元素的 value、checked、selected 特性的初始值而总是将 Vue 实例的数据作为数据来源 -+ v-model 会忽略所有表单元素的 value、checked、selected 特性的初始值而总是将 Vue 实例的数据作为数据来源 #### 基础用法 +# v-model 在内部为不同的输入元素使用不同的属性并抛出不同的事件: -1. v-model 在内部为不同的输入元素使用不同的属性并抛出不同的事件: + text 和 textarea 元素使用 value 属性和 input 事件; + checkbox 和 radio 使用 checked 属性和 change 事件; + select 字段将 value 作为 prop 并将 change 作为事件。 +``` -+ text 和 textarea 元素使用 value 属性和 input 事件; -+ checkbox 和 radio 使用 checked 属性和 change 事件; -+ select 字段将 value 作为 prop 并将 change 作为事件。 +## 代码块 + +```sh + + # 代码 (in6-5html) -代码如下(in6-5html) -```
            @@ -58,7 +61,9 @@ ``` -``` + +```sh + + # 代码 (script) ``` -注意:组件的data是一个函数通过返回值来实现 -通过this.$refs.one我们可以获得ref="one"的组件以及其内的所以内容, +## 注意: + +```sh +## 1. 组件的data是一个函数通过返回值来实现 + +## 2. 通过this.$refs.one我们可以获得ref="one"的组件以及其内的所以内容, -this.$refs.one.number获取了组件中的number +## 3. this.$refs.one.number获取了组件中的number +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.09\357\274\210Vue Lci\357\274\211.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.09\357\274\210Vue Lci\357\274\211.md" index 50ace09e81d3936783595ae51413bb249ee864a5..28c05374fb5ab26b2fe72ab98cac3577e578e3cb 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.09\357\274\210Vue Lci\357\274\211.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.09\357\274\210Vue Lci\357\274\211.md" @@ -1,42 +1,47 @@ -## Vue Lci +# Vue Lci -1. 修改linux文件权限 +## linux +```sh ++ # 1. 修改linux文件权限 -2. chmod -R 777 文件夹名/ +- # 2. chmod -R 777 文件夹名/ -3. 修改Host文件 ++ # 3. 修改Host文件 -4. 修改 host 权限 - -5. 右键-属性-安全-高级-更改权限-添加-选择主体-高级-立即查找-选择Administrator-保存 +- # 4. 修改 host 权限 ++ # 5. 右键-属性-安全-高级-更改权限-添加-选择主体-高级-立即查找-选择Administrator-保存 ``` + +## host 文件位置 +```sh // host 文件位置 C:\Windows\System32\drivers\etc ``` -1. 父传子有哪些方式 -``` +## 之间关系 +```sh +## 1. 父传子有哪些方式 用props传值 -``` -2. 子传父有哪些方式 -``` + +## 2. 子传父有哪些方式 + 通过$emit触发自定义事件 -``` -3. 如何让 CSS 只在当前组件中起作用 -``` + +## 3. 如何让 CSS 只在当前组件中起作用 + 利用scoped来限制 -``` -4. keep-alive 的作用是什么 -``` + +## 4. keep-alive 的作用是什么 + ​保留组件状态,避免组件重新渲染 -``` -5. vue中如何获取DOM -``` + +## 5. vue中如何获取DOM + ​ $refs属性 -``` -6. 请说出 Vue CLI 项目中src目录每个文件夹的文件的用法​assets:放静态资源 -``` + +## 6. 请说出 Vue CLI 项目中src目录每个文件夹的文件的用法​assets:放静态资源 + ​ components:放组件 ​ router:定义路由相关配置 @@ -46,17 +51,17 @@ C:\Windows\System32\drivers\etc ​ app.vue:主组件 ​ main.js:入口文件 -``` -7. 单页面应用的优缺点​ 优点: -``` + +## 7. 单页面应用的优缺点​ 优点: + 前后端分离开发,提高开发效率 业务场景切换时,局部更新结构 用户体验好,更加接近本地应用 -``` -8. 缺点: -``` + +## 8. 缺点: + 不利于SEO 首次加载速度较慢 页面复杂度较高 router和route的区别 router为VueRouter的实例,常用router.push方法来导航到不同URL @@ -66,5 +71,6 @@ $route为当前router跳转对象,可以获取name、path、params等属性 怎么定义 vue-router 的动态路由? 怎么获取传过来的值? 将路径中的某个部分使用':'标记,即可设置为动态路由 通过$route.params来获取值 -``` -9. vue-router有几种模式,分别是什么 两种模式,分别为hash模式和history模式 \ No newline at end of file + +## 9. vue-router有几种模式,分别是什么 两种模式,分别为hash模式和history模式 +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.11\357\274\210Vue CLI \351\203\250\347\275\262\345\210\260\346\234\215\345\212\241\345\231\250\357\274\211.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.11\357\274\210Vue CLI \351\203\250\347\275\262\345\210\260\346\234\215\345\212\241\345\231\250\357\274\211.md" index 72253948aaf3378ca7df4915e1483f923aca9b83..1ae45cddcf8c47a91a68d76e4b05f097d9e0f242 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.11\357\274\210Vue CLI \351\203\250\347\275\262\345\210\260\346\234\215\345\212\241\345\231\250\357\274\211.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.11\357\274\210Vue CLI \351\203\250\347\275\262\345\210\260\346\234\215\345\212\241\345\231\250\357\274\211.md" @@ -1,7 +1,7 @@ -## Vue CLI 部署在服务器 +# Vue CLI 部署在服务器 ### 端口修改配置文件 -``` +```sh module.exports = { devServer: { port: 5050, // 端口 @@ -10,24 +10,28 @@ module.exports = { }; ``` -+ 一些Vue命令 -+ 安装vue/cli -``` +```sh ++ # 一些Vue命令 ++ # 安装vue/cli + npm install -g @vue/cli -``` + ### OR -``` + yarn global add @vue/cli 更新vue/cli -``` -``` + npm update -g @vue/cli -``` + ### OR -``` + yarn global upgrade --latest @vue/cli 创建vue项目 ``` + +```sh +## 命令 + vue create myVueProject // 你的要创建Vue项目 cd myVueProject // 进入你的项目文件夹 @@ -39,17 +43,19 @@ yarn serve // 启动你的vue项目 yarn build // 打包你的项目,文件会保存到dist文件夹里面 cp -r 文件名 /位置/修改后的文件名 - +``` # OR +```sh +# 命令 + +## 方法一 使用 Visual Studio Code 在VS code 里直接安装 -方法一 使用 Visual Studio Code 在VS code 里直接安装 -~~~html -1. 安装vue/cli ++ # 1. 安装vue/cli npm install -g @vue/cli -2. 创建vue项目 ++ # 2. 创建vue项目 vue create myVueProject // 你的要创建Vue项目 @@ -58,6 +64,6 @@ cd myVueProject // 进入你的项目文件夹 yarn add vue-router // 安装vue-router yarn serve // 启动你的vue项目 -~~~ -方法二 使用 cmd 安裝,注意修改文件夹的位置,命令一样 \ No newline at end of file +## 方法二 使用 cmd 安裝,注意修改文件夹的位置,命令一样 +``` \ No newline at end of file diff --git "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.12\357\274\210Vue \344\275\277\347\224\250\347\273\204\344\273\266\357\274\211.md" "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.12\357\274\210Vue \344\275\277\347\224\250\347\273\204\344\273\266\357\274\211.md" index f0a4ee7813b43e2dd2c43f9655c23c99ce6cb787..0397eaaf046c7ab07eb991aa3e8df6b7555c701b 100644 --- "a/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.12\357\274\210Vue \344\275\277\347\224\250\347\273\204\344\273\266\357\274\211.md" +++ "b/\346\242\201\350\211\272\347\274\244/Vue - 2021.06.12\357\274\210Vue \344\275\277\347\224\250\347\273\204\344\273\266\357\274\211.md" @@ -1,10 +1,9 @@ -## Vue CLI使用组件 +# Vue CLI使用组件 -### 1. 完成Vue Cli项目部署 +## 完成Vue Cli项目部署 +```sh +### 1. 在src-components新建Vue文件夹 -### 2. 在src-components新建Vue文件夹 - -``` -``` -+ 注意:data返回的是一个函数 -### 3. 在src自己创建的App.Vue里引Vue文件 -``` ++ # 注意:data返回的是一个函数 + + + +### 2. 在src自己创建的App.Vue里引Vue文件 +