├── .gitattributes ├── .gitignore ├── MyBlog.IRepository ├── IBaseRepository.cs ├── IBlogNewsRepository.cs ├── ITypeInfoRepository.cs ├── IWriterInfoRepository.cs └── MyBlog.IRepository.csproj ├── MyBlog.IService ├── IBaseService.cs ├── IBlogNewsService.cs ├── ITypeInfoService.cs ├── IWriterInfoService.cs └── MyBlog.IService.csproj ├── MyBlog.JWT ├── Controllers │ ├── AuthoizeController.cs │ └── WeatherForecastController.cs ├── MyBlog.JWT.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── Utility │ ├── ApiResult │ │ ├── ApiResult.cs │ │ └── ApiResultHelper.cs │ └── _MD5 │ │ └── MD5Helper.cs ├── WeatherForecast.cs ├── appsettings.Development.json └── appsettings.json ├── MyBlog.Model ├── BaseId.cs ├── BlogNews.cs ├── DTO │ ├── BlogNewsDTO.cs │ └── WriterDTO.cs ├── MyBlog.Model.csproj ├── TypeInfo.cs └── WriterInfo.cs ├── MyBlog.Repository ├── BaseRepository.cs ├── BlogNewsRepository.cs ├── MyBlog.Repository.csproj ├── TypeInfoRepository.cs └── WriterInfoRepository.cs ├── MyBlog.Service ├── BaseService.cs ├── BlogNewsService.cs ├── MyBlog.Service.csproj ├── TypeInfoService.cs └── WriterInfoService.cs ├── MyBlog.WebApi ├── Controllers │ ├── BlogNewsController.cs │ ├── TestController.cs │ ├── TypeController.cs │ ├── WeatherForecastController.cs │ └── WriterInfoController.cs ├── MyBlog.WebApi.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── Utility │ ├── ApiResult │ │ ├── ApiResult.cs │ │ └── ApiResultHelper.cs │ ├── _AutoMapper │ │ └── CustomAutoMapperProfile.cs │ └── _MD5 │ │ └── MD5Helper.cs ├── WeatherForecast.cs ├── appsettings.Development.json └── appsettings.json ├── MyBlog.sln └── asp.net core个人博客.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /MyBlog.IRepository/IBaseRepository.cs: -------------------------------------------------------------------------------- 1 | using SqlSugar; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace MyBlog.IRepository 9 | { 10 | public interface IBaseRepository where TEntity:class,new() 11 | { 12 | Task CreateAsync(TEntity entity); 13 | Task DeleteAsync(int id); 14 | Task EditAsync(TEntity entity); 15 | Task FindAsync(int id); 16 | Task FindAsync(Expression> func); 17 | /// 18 | /// 查询全部的数据 19 | /// 20 | /// 21 | Task> QueryAsync(); 22 | /// 23 | /// 自定义条件查询 24 | /// 25 | /// 26 | /// 27 | Task> QueryAsync(Expression> func); 28 | /// 29 | /// 分页查询 30 | /// 31 | /// 32 | /// 33 | /// 34 | /// 35 | Task> QueryAsync(int page, int size, RefAsync total); 36 | /// 37 | /// 自定义条件分页查询 38 | /// 39 | /// 40 | /// 41 | /// 42 | /// 43 | /// 44 | Task> QueryAsync(Expression> func, int page, int size, RefAsync total); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MyBlog.IRepository/IBlogNewsRepository.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.Model; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace MyBlog.IRepository 7 | { 8 | public interface IBlogNewsRepository:IBaseRepository 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.IRepository/ITypeInfoRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | 6 | namespace MyBlog.IRepository 7 | { 8 | public interface ITypeInfoRepository:IBaseRepository 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.IRepository/IWriterInfoRepository.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.Model; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace MyBlog.IRepository 7 | { 8 | public interface IWriterInfoRepository:IBaseRepository 9 | { 10 | void Mthod(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /MyBlog.IRepository/MyBlog.IRepository.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /MyBlog.IService/IBaseService.cs: -------------------------------------------------------------------------------- 1 | using SqlSugar; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace MyBlog.IService 9 | { 10 | public interface IBaseService where TEntity:class,new() 11 | { 12 | Task CreateAsync(TEntity entity); 13 | Task DeleteAsync(int id); 14 | Task EditAsync(TEntity entity); 15 | Task FindAsync(int id); 16 | Task FindAsync(Expression> func); 17 | /// 18 | /// 查询全部的数据 19 | /// 20 | /// 21 | Task> QueryAsync(); 22 | /// 23 | /// 自定义条件查询 24 | /// 25 | /// 26 | /// 27 | Task> QueryAsync(Expression> func); 28 | /// 29 | /// 分页查询 30 | /// 31 | /// 32 | /// 33 | /// 34 | /// 35 | Task> QueryAsync(int page, int size, RefAsync total); 36 | /// 37 | /// 自定义条件分页查询 38 | /// 39 | /// 40 | /// 41 | /// 42 | /// 43 | /// 44 | Task> QueryAsync(Expression> func, int page, int size, RefAsync total); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MyBlog.IService/IBlogNewsService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.Model; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace MyBlog.IService 7 | { 8 | public interface IBlogNewsService:IBaseService 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.IService/ITypeInfoService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.Model; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace MyBlog.IService 7 | { 8 | public interface ITypeInfoService:IBaseService 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.IService/IWriterInfoService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.Model; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace MyBlog.IService 7 | { 8 | public interface IWriterInfoService:IBaseService 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.IService/MyBlog.IService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /MyBlog.JWT/Controllers/AuthoizeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.IdentityModel.Tokens; 4 | using MyBlog.IService; 5 | using MyBlog.JWT.Utility._MD5; 6 | using MyBlog.JWT.Utility.ApiResult; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.IdentityModel.Tokens.Jwt; 10 | using System.Linq; 11 | using System.Security.Claims; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace MyBlog.JWT.Controllers 16 | { 17 | [Route("api/[controller]")] 18 | [ApiController] 19 | public class AuthoizeController : ControllerBase 20 | { 21 | private readonly IWriterInfoService _iWriterInfoService; 22 | public AuthoizeController(IWriterInfoService iWriterInfoService) 23 | { 24 | _iWriterInfoService = iWriterInfoService; 25 | } 26 | [HttpPost("Login")] 27 | public async Task Login(string username,string userpwd) 28 | { 29 | //加密后的密码 123456 =>sdlkfjkldsjidaifdaskfaj == sdlkfjkldsjidaifdaskfaj 30 | string pwd = MD5Helper.MD5Encrypt32(userpwd); 31 | //数据校验 32 | var writer= await _iWriterInfoService.FindAsync(c => c.UserName == username && c.UserPwd == pwd); 33 | if (writer != null) 34 | { 35 | //登陆成功 36 | var claims = new Claim[] 37 | { 38 | new Claim(ClaimTypes.Name, writer.Name), 39 | new Claim("Id", writer.Id.ToString()), 40 | new Claim("UserName", writer.UserName) 41 | //不能放敏感信息 42 | }; 43 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")); 44 | //issuer代表颁发Token的Web应用程序,audience是Token的受理者 45 | var token = new JwtSecurityToken( 46 | issuer: "http://localhost:6060", 47 | audience: "http://localhost:5000", 48 | claims: claims, 49 | notBefore: DateTime.Now, 50 | expires: DateTime.Now.AddHours(1), 51 | signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) 52 | ); 53 | var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); 54 | return ApiResultHelper.Success(jwtToken); 55 | } 56 | else 57 | { 58 | return ApiResultHelper.Error("账号或密码错误"); 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /MyBlog.JWT/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace MyBlog.JWT.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public WeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MyBlog.JWT/MyBlog.JWT.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /MyBlog.JWT/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace MyBlog.JWT 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /MyBlog.JWT/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:50788", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "MyBlog.JWT": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "http://localhost:6060", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /MyBlog.JWT/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Microsoft.Extensions.Logging; 8 | using Microsoft.OpenApi.Models; 9 | using MyBlog.IRepository; 10 | using MyBlog.IService; 11 | using MyBlog.Repository; 12 | using MyBlog.Service; 13 | using SqlSugar.IOC; 14 | using System; 15 | using System.Collections.Generic; 16 | using System.Linq; 17 | using System.Threading.Tasks; 18 | 19 | namespace MyBlog.JWT 20 | { 21 | public class Startup 22 | { 23 | public Startup(IConfiguration configuration) 24 | { 25 | Configuration = configuration; 26 | } 27 | 28 | public IConfiguration Configuration { get; } 29 | 30 | // This method gets called by the runtime. Use this method to add services to the container. 31 | public void ConfigureServices(IServiceCollection services) 32 | { 33 | 34 | services.AddControllers(); 35 | services.AddSwaggerGen(c => 36 | { 37 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyBlog.JWT", Version = "v1" }); 38 | }); 39 | #region SqlSugarIOC 40 | services.AddSqlSugar(new IocConfig() 41 | { 42 | ConnectionString = this.Configuration["SqlConn"], 43 | DbType = IocDbType.SqlServer, 44 | IsAutoCloseConnection = true 45 | }); 46 | #endregion 47 | services.AddScoped(); 48 | services.AddScoped(); 49 | } 50 | 51 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 52 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 53 | { 54 | if (env.IsDevelopment()) 55 | { 56 | app.UseDeveloperExceptionPage(); 57 | app.UseSwagger(); 58 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyBlog.JWT v1")); 59 | } 60 | 61 | app.UseRouting(); 62 | 63 | app.UseAuthorization(); 64 | 65 | app.UseEndpoints(endpoints => 66 | { 67 | endpoints.MapControllers(); 68 | }); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /MyBlog.JWT/Utility/ApiResult/ApiResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace MyBlog.JWT.Utility.ApiResult 7 | { 8 | public class ApiResult 9 | { 10 | public int Code { get; set; } 11 | public string Msg { get; set; } 12 | public int Total { get; set; } 13 | public dynamic Data { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /MyBlog.JWT/Utility/ApiResult/ApiResultHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace MyBlog.JWT.Utility.ApiResult 7 | { 8 | public static class ApiResultHelper 9 | { 10 | //成功后返回的数据 11 | public static ApiResult Success(dynamic data) 12 | { 13 | return new ApiResult 14 | { 15 | Code = 200, 16 | Data = data, 17 | Msg = "操作成功", 18 | Total = 0 19 | }; 20 | } 21 | public static ApiResult Success(dynamic data, int total) 22 | { 23 | return new ApiResult 24 | { 25 | Code = 200, 26 | Data = data, 27 | Msg = "操作成功", 28 | Total = total 29 | }; 30 | } 31 | public static ApiResult Error(string msg) 32 | { 33 | return new ApiResult 34 | { 35 | Code = 500, 36 | Data = null, 37 | Msg = msg, 38 | Total = 0 39 | }; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /MyBlog.JWT/Utility/_MD5/MD5Helper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Cryptography; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace MyBlog.JWT.Utility._MD5 9 | { 10 | public static class MD5Helper 11 | { 12 | public static string MD5Encrypt32(string password) 13 | { 14 | string pwd = ""; 15 | MD5 md5 = MD5.Create(); 16 | byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); 17 | for (int i = 0; i < s.Length; i++) 18 | { 19 | pwd = pwd + s[i].ToString("X"); 20 | } 21 | return pwd; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /MyBlog.JWT/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MyBlog.JWT 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /MyBlog.JWT/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /MyBlog.JWT/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "SqlConn": "Server=.;Database=MyBlogDB;Trusted_Connection=True;" 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.Model/BaseId.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using SqlSugar; 5 | namespace MyBlog.Model 6 | { 7 | public class BaseId 8 | { 9 | [SugarColumn(IsIdentity=true, IsPrimaryKey=true)] 10 | public int Id { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /MyBlog.Model/BlogNews.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using SqlSugar; 5 | namespace MyBlog.Model 6 | { 7 | public class BlogNews:BaseId 8 | { 9 | //nvarchar带中文比较好 10 | [SugarColumn(ColumnDataType ="nvarchar(30)")] 11 | public string Title { get; set; } 12 | [SugarColumn(ColumnDataType ="text")] 13 | public string Content { get; set; } 14 | public DateTime Time { get; set; } 15 | public int BrowseCount { get; set; } 16 | public int LikeCount { get; set; } 17 | 18 | public int TypeId { get; set; } 19 | public int WriterId { get; set; } 20 | /// 21 | /// 类型,不映射到数据库 22 | /// 23 | [SugarColumn(IsIgnore =true)] 24 | public TypeInfo TypeInfo { get; set; } 25 | 26 | [SugarColumn(IsIgnore = true)] 27 | public WriterInfo WriterInfo { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /MyBlog.Model/DTO/BlogNewsDTO.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace MyBlog.Model.DTO 6 | { 7 | public class BlogNewsDTO 8 | { 9 | public int Id { get; set; } 10 | public string Title { get; set; } 11 | public string Content { get; set; } 12 | public DateTime Time { get; set; } 13 | public int BrowseCount { get; set; } 14 | public int LikeCount { get; set; } 15 | public int TypeId { get; set; } 16 | public int WriterId { get; set; } 17 | public string TypeName { get; set; } 18 | public string WriterName { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /MyBlog.Model/DTO/WriterDTO.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace MyBlog.Model.DTO 6 | { 7 | public class WriterDTO 8 | { 9 | public int Id { get; set; } 10 | public string Name { get; set; } 11 | public string UserName { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /MyBlog.Model/MyBlog.Model.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /MyBlog.Model/TypeInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using SqlSugar; 5 | namespace MyBlog.Model 6 | { 7 | public class TypeInfo:BaseId 8 | { 9 | [SugarColumn(ColumnDataType ="nvarchar(12)")] 10 | public string Name { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /MyBlog.Model/WriterInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using SqlSugar; 5 | namespace MyBlog.Model 6 | { 7 | public class WriterInfo:BaseId 8 | { 9 | [SugarColumn(ColumnDataType ="nvarchar(12)")] 10 | public string Name { get; set; } 11 | [SugarColumn(ColumnDataType = "nvarchar(16)")] 12 | public string UserName { get; set; } 13 | [SugarColumn(ColumnDataType = "nvarchar(64)")] 14 | public string UserPwd { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /MyBlog.Repository/BaseRepository.cs: -------------------------------------------------------------------------------- 1 |  2 | using MyBlog.IRepository; 3 | using MyBlog.Model; 4 | using SqlSugar; 5 | using SqlSugar.IOC; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq.Expressions; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace MyBlog.Repository 13 | { 14 | public class BaseRepository : SimpleClient, IBaseRepository where TEntity : class, new() 15 | { 16 | public BaseRepository(ISqlSugarClient context=null):base(context) 17 | { 18 | base.Context = DbScoped.Sugar; 19 | //// 创建数据库 20 | //base.Context.DbMaintenance.CreateDatabase(); 21 | //// 创建表 22 | //base.Context.CodeFirst.InitTables( 23 | // typeof(BlogNews), 24 | // typeof(TypeInfo), 25 | // typeof(WriterInfo) 26 | // ); 27 | } 28 | public async Task CreateAsync(TEntity entity) 29 | { 30 | return await base.InsertAsync(entity); 31 | } 32 | public async Task DeleteAsync(int id) 33 | { 34 | return await base.DeleteByIdAsync(id); 35 | } 36 | 37 | public async Task EditAsync(TEntity entity) 38 | { 39 | return await base.UpdateAsync(entity); 40 | } 41 | //导航查询 42 | public virtual async Task FindAsync(int id) 43 | { 44 | return await base.GetByIdAsync(id); 45 | } 46 | 47 | public async Task FindAsync(Expression> func) 48 | { 49 | return await base.GetSingleAsync(func); 50 | } 51 | 52 | public virtual async Task> QueryAsync() 53 | { 54 | return await base.GetListAsync(); 55 | } 56 | 57 | public virtual async Task> QueryAsync(Expression> func) 58 | { 59 | return await base.GetListAsync(func); 60 | } 61 | 62 | public virtual async Task> QueryAsync(int page, int size, RefAsync total) 63 | { 64 | return await base.Context.Queryable() 65 | .ToPageListAsync(page, size, total); 66 | } 67 | 68 | public virtual async Task> QueryAsync(Expression> func, int page, int size, RefAsync total) 69 | { 70 | return await base.Context.Queryable() 71 | .Where(func) 72 | .ToPageListAsync(page, size, total); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /MyBlog.Repository/BlogNewsRepository.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.Model; 3 | using SqlSugar; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace MyBlog.Repository 11 | { 12 | public class BlogNewsRepository:BaseRepository,IBlogNewsRepository 13 | { 14 | public async override Task> QueryAsync() 15 | { 16 | return await base.Context.Queryable() 17 | .Mapper(c => c.TypeInfo, c => c.TypeId, c => c.TypeInfo.Id) 18 | .Mapper(c=>c.WriterInfo,c=>c.WriterId,c=>c.WriterInfo.Id) 19 | .ToListAsync(); 20 | } 21 | public async override Task> QueryAsync(Expression> func) 22 | { 23 | return await base.Context.Queryable() 24 | .Where(func) 25 | .Mapper(c => c.TypeInfo, c => c.TypeId, c => c.TypeInfo.Id) 26 | .Mapper(c => c.WriterInfo, c => c.WriterId, c => c.WriterInfo.Id) 27 | .ToListAsync(); 28 | } 29 | public async override Task> QueryAsync(int page, int size, RefAsync total) 30 | { 31 | return await base.Context.Queryable() 32 | .Mapper(c => c.WriterInfo, c => c.WriterId, c => c.WriterInfo.Id) 33 | .Mapper(c => c.TypeInfo, c => c.TypeId, c => c.TypeInfo.Id) 34 | .ToPageListAsync(page, size, total); 35 | } 36 | public async override Task> QueryAsync(Expression> func, int page, int size, RefAsync total) 37 | { 38 | return await base.Context.Queryable() 39 | .Where(func) 40 | .Mapper(c=>c.WriterInfo,c=>c.WriterId,c=>c.WriterInfo.Id) 41 | .Mapper(c=>c.TypeInfo, c => c.TypeId, c => c.TypeInfo.Id) 42 | .ToPageListAsync(page, size, total); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /MyBlog.Repository/MyBlog.Repository.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /MyBlog.Repository/TypeInfoRepository.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.Model; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace MyBlog.Repository 8 | { 9 | public class TypeInfoRepository:BaseRepository,ITypeInfoRepository 10 | { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /MyBlog.Repository/WriterInfoRepository.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.Model; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace MyBlog.Repository 8 | { 9 | public class WriterInfoRepository : BaseRepository, IWriterInfoRepository 10 | { 11 | public void Mthod() 12 | { 13 | throw new NotImplementedException(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /MyBlog.Service/BaseService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.IService; 3 | using SqlSugar; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using System.Threading.Tasks; 8 | 9 | namespace MyBlog.Service 10 | { 11 | public class BaseService : IBaseService where TEntity : class, new() 12 | { 13 | //从子类的构造函数中传入 14 | protected IBaseRepository _iBaseRepository; 15 | 16 | public async Task CreateAsync(TEntity entity) 17 | { 18 | return await _iBaseRepository.CreateAsync(entity); 19 | } 20 | 21 | public async Task DeleteAsync(int id) 22 | { 23 | return await _iBaseRepository.DeleteAsync(id); 24 | } 25 | 26 | public async Task EditAsync(TEntity entity) 27 | { 28 | return await _iBaseRepository.EditAsync(entity); 29 | } 30 | 31 | public async Task FindAsync(int id) 32 | { 33 | return await _iBaseRepository.FindAsync(id); 34 | } 35 | 36 | public async Task FindAsync(Expression> func) 37 | { 38 | return await _iBaseRepository.FindAsync(func); 39 | } 40 | 41 | public async Task> QueryAsync() 42 | { 43 | return await _iBaseRepository.QueryAsync(); 44 | } 45 | 46 | public async Task> QueryAsync(Expression> func) 47 | { 48 | return await _iBaseRepository.QueryAsync(func); 49 | } 50 | 51 | public async Task> QueryAsync(int page, int size, RefAsync total) 52 | { 53 | return await _iBaseRepository.QueryAsync(page, size, total); 54 | } 55 | 56 | public async Task> QueryAsync(Expression> func, int page, int size, RefAsync total) 57 | { 58 | return await _iBaseRepository.QueryAsync(func, page, size, total); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /MyBlog.Service/BlogNewsService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.IService; 3 | using MyBlog.Model; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace MyBlog.Service 9 | { 10 | public class BlogNewsService:BaseService,IBlogNewsService 11 | { 12 | private readonly IBlogNewsRepository _iBlogNewsRepository; 13 | public BlogNewsService(IBlogNewsRepository iBlogNewsRepository) 14 | { 15 | base._iBaseRepository = iBlogNewsRepository; 16 | _iBlogNewsRepository = iBlogNewsRepository; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MyBlog.Service/MyBlog.Service.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /MyBlog.Service/TypeInfoService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.IService; 3 | using MyBlog.Model; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace MyBlog.Service 9 | { 10 | public class TypeInfoService:BaseService,ITypeInfoService 11 | { 12 | private readonly ITypeInfoRepository _iTypeInfoRepository; 13 | public TypeInfoService(ITypeInfoRepository iTypeInfoRepository) 14 | { 15 | base._iBaseRepository = iTypeInfoRepository; 16 | _iTypeInfoRepository = iTypeInfoRepository; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MyBlog.Service/WriterInfoService.cs: -------------------------------------------------------------------------------- 1 | using MyBlog.IRepository; 2 | using MyBlog.IService; 3 | using MyBlog.Model; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace MyBlog.Service 9 | { 10 | public class WriterInfoService:BaseService,IWriterInfoService 11 | { 12 | private readonly IWriterInfoRepository _iWriterInfoRepository; 13 | public WriterInfoService(IWriterInfoRepository iWriterInfoRepository) 14 | { 15 | base._iBaseRepository = iWriterInfoRepository; 16 | _iWriterInfoRepository = iWriterInfoRepository; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Controllers/BlogNewsController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using MyBlog.IService; 6 | using MyBlog.Model; 7 | using MyBlog.Model.DTO; 8 | using MyBlog.WebApi.Utility.ApiResult; 9 | using SqlSugar; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Linq; 13 | using System.Threading.Tasks; 14 | 15 | namespace MyBlog.WebApi.Controllers 16 | { 17 | [Route("api/[controller]")] 18 | [ApiController] 19 | [Authorize] 20 | public class BlogNewsController : ControllerBase 21 | { 22 | private readonly IBlogNewsService _iBlogNewsService; 23 | public BlogNewsController(IBlogNewsService iBlogNewsService) 24 | { 25 | this._iBlogNewsService = iBlogNewsService; 26 | } 27 | [HttpGet("BlogNews")] 28 | public async Task> GetBlogNews() 29 | { 30 | int id = Convert.ToInt32(this.User.FindFirst("Id").Value); 31 | var data= await _iBlogNewsService.QueryAsync(c=>c.WriterId==id); 32 | if (data == null) return ApiResultHelper.Error("没有更多的文章"); 33 | return ApiResultHelper.Success(data); 34 | } 35 | /// 36 | /// 添加文章 37 | /// 38 | /// 39 | /// 40 | /// 41 | [HttpPost("Create")] 42 | public async Task> Create(string title,string content,int typeid) 43 | { 44 | //数据验证 45 | BlogNews blogNews = new BlogNews 46 | { 47 | BrowseCount = 0, 48 | Content = content, 49 | LikeCount = 0, 50 | Time = DateTime.Now, 51 | Title = title, 52 | TypeId = typeid, 53 | WriterId = Convert.ToInt32(this.User.FindFirst("Id").Value) 54 | }; 55 | bool b = await _iBlogNewsService.CreateAsync(blogNews); 56 | if (!b) return ApiResultHelper.Error("添加失败,服务器发生错误"); 57 | return ApiResultHelper.Success(blogNews); 58 | } 59 | [HttpDelete("Delete")] 60 | public async Task> Delete(int id) 61 | { 62 | bool b =await _iBlogNewsService.DeleteAsync(id); 63 | if (!b) return ApiResultHelper.Error("删除失败"); 64 | return ApiResultHelper.Success(b); 65 | } 66 | [HttpPut("Edit")] 67 | public async Task> Edit(int id,string title,string content,int typeid) 68 | { 69 | var blogNews= await _iBlogNewsService.FindAsync(id); 70 | if (blogNews == null) return ApiResultHelper.Error("没有找到该文章"); 71 | blogNews.Title = title; 72 | blogNews.Content = content; 73 | blogNews.TypeId = typeid; 74 | bool b = await _iBlogNewsService.EditAsync(blogNews); 75 | if (!b) return ApiResultHelper.Error("修改失败"); 76 | return ApiResultHelper.Success(blogNews); 77 | } 78 | [HttpGet("BlogNewsPage")] 79 | public async Task GetBlogNewsPage([FromServices] IMapper iMapper,int page,int size) 80 | { 81 | RefAsync total = 0; 82 | var blognews =await _iBlogNewsService.QueryAsync(page, size, total); 83 | try 84 | { 85 | var blognewsDTO = iMapper.Map>(blognews); 86 | return ApiResultHelper.Success(blognewsDTO, total); 87 | } 88 | catch (Exception) 89 | { 90 | return ApiResultHelper.Error("AutoMapper映射错误"); 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Controllers/TestController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace MyBlog.WebApi.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [ApiController] 13 | public class TestController : ControllerBase 14 | { 15 | [HttpGet("NoAuthorize")] 16 | public string NoAuthorize() 17 | { 18 | return "this is NoAuthorize"; 19 | } 20 | [Authorize] 21 | [HttpGet("Authorize")] 22 | public string Authorize() 23 | { 24 | return "this is Authorize"; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Controllers/TypeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using MyBlog.IService; 5 | using MyBlog.Model; 6 | using MyBlog.WebApi.Utility.ApiResult; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading.Tasks; 11 | 12 | namespace MyBlog.WebApi.Controllers 13 | { 14 | [Route("api/[controller]")] 15 | [ApiController] 16 | [Authorize] 17 | public class TypeController : ControllerBase 18 | { 19 | private readonly ITypeInfoService _iTypeInfoService; 20 | public TypeController(ITypeInfoService iTypeInfoService) 21 | { 22 | this._iTypeInfoService = iTypeInfoService; 23 | } 24 | [HttpGet("Types")] 25 | public async Task Types() 26 | { 27 | var types =await _iTypeInfoService.QueryAsync(); 28 | if(types.Count==0) return ApiResultHelper.Error("没有更多的类型"); 29 | return ApiResultHelper.Success(types); 30 | } 31 | [HttpPost("Create")] 32 | public async Task Create(string name) 33 | { 34 | #region 数据验证 35 | if (String.IsNullOrWhiteSpace(name)) return ApiResultHelper.Error("文章类型名不能为空"); 36 | #endregion 37 | TypeInfo type = new TypeInfo 38 | { 39 | Name = name 40 | }; 41 | bool b =await _iTypeInfoService.CreateAsync(type); 42 | if (!b) return ApiResultHelper.Error("添加失败"); 43 | return ApiResultHelper.Success(b); 44 | } 45 | [HttpPut("Edit")] 46 | public async Task Edit(int id,string name) 47 | { 48 | var type =await _iTypeInfoService.FindAsync(id); 49 | if (type == null) return ApiResultHelper.Error("没有找到该文章类型"); 50 | type.Name = name; 51 | bool b = await _iTypeInfoService.EditAsync(type); 52 | if (!b) return ApiResultHelper.Error("修改失败"); 53 | return ApiResultHelper.Success(type); 54 | } 55 | [HttpDelete("Delete")] 56 | public async Task Delete(int id) 57 | { 58 | bool b = await _iTypeInfoService.DeleteAsync(id); 59 | if (!b) return ApiResultHelper.Error("删除失败"); 60 | return ApiResultHelper.Success(b); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace MyBlog.WebApi.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public WeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Controllers/WriterInfoController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using MyBlog.IService; 6 | using MyBlog.Model; 7 | using MyBlog.Model.DTO; 8 | using MyBlog.WebApi.Utility._MD5; 9 | using MyBlog.WebApi.Utility.ApiResult; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Linq; 13 | using System.Threading.Tasks; 14 | 15 | namespace MyBlog.WebApi.Controllers 16 | { 17 | [Route("api/[controller]")] 18 | [ApiController] 19 | [Authorize] 20 | public class WriterInfoController : ControllerBase 21 | { 22 | private readonly IWriterInfoService _iWriterInfoService; 23 | public WriterInfoController(IWriterInfoService iWriterInfoService) 24 | { 25 | _iWriterInfoService = iWriterInfoService; 26 | } 27 | [HttpPost("Create")] 28 | public async Task Create(string name,string username,string userpwd) 29 | { 30 | //数据校验 31 | WriterInfo writer = new WriterInfo 32 | { 33 | Name = name, 34 | //加密密码 35 | UserPwd =MD5Helper.MD5Encrypt32(userpwd), 36 | UserName = username 37 | }; 38 | //判断数据库中是否已经存在账号跟要添加的账号相同的数据 39 | var oldWriter= await _iWriterInfoService.FindAsync(c => c.UserName == username); 40 | if (oldWriter != null) return ApiResultHelper.Error("账号已经存在"); 41 | 42 | bool b =await _iWriterInfoService.CreateAsync(writer); 43 | if (!b) return ApiResultHelper.Error("添加失败"); 44 | return ApiResultHelper.Success(writer); 45 | } 46 | [HttpPut("Edit")] 47 | public async Task Edit(string name) 48 | { 49 | int id =Convert.ToInt32(this.User.FindFirst("Id").Value); 50 | var writer=await _iWriterInfoService.FindAsync(id); 51 | writer.Name = name; 52 | bool b =await _iWriterInfoService.EditAsync(writer); 53 | if (!b) return ApiResultHelper.Error("修改失败"); 54 | return ApiResultHelper.Success("修改成功"); 55 | } 56 | [AllowAnonymous] 57 | [HttpGet("FindWriter")] 58 | public async Task FindWriter([FromServices]IMapper iMapper,int id) 59 | { 60 | var writer =await _iWriterInfoService.FindAsync(id); 61 | var writerDTO= iMapper.Map(writer); 62 | return ApiResultHelper.Success(writerDTO); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /MyBlog.WebApi/MyBlog.WebApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace MyBlog.WebApi 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:56894", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "MyBlog.WebApi": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Startup.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1397771033/MyBlog/f69c0fa0d01025b7274800d638eb2c84d94a8ced/MyBlog.WebApi/Startup.cs -------------------------------------------------------------------------------- /MyBlog.WebApi/Utility/ApiResult/ApiResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace MyBlog.WebApi.Utility.ApiResult 7 | { 8 | public class ApiResult 9 | { 10 | public int Code { get; set; } 11 | public string Msg { get; set; } 12 | public int Total { get; set; } 13 | public dynamic Data { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Utility/ApiResult/ApiResultHelper.cs: -------------------------------------------------------------------------------- 1 | using SqlSugar; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace MyBlog.WebApi.Utility.ApiResult 8 | { 9 | public static class ApiResultHelper 10 | { 11 | //成功后返回的数据 12 | public static ApiResult Success(dynamic data) 13 | { 14 | return new ApiResult 15 | { 16 | Code = 200, 17 | Data = data, 18 | Msg = "操作成功", 19 | Total = 0 20 | }; 21 | } 22 | public static ApiResult Success(dynamic data, RefAsync total) 23 | { 24 | return new ApiResult 25 | { 26 | Code = 200, 27 | Data = data, 28 | Msg = "操作成功", 29 | Total = total 30 | }; 31 | } 32 | public static ApiResult Error(string msg) 33 | { 34 | return new ApiResult 35 | { 36 | Code = 500, 37 | Data = null, 38 | Msg = msg, 39 | Total = 0 40 | }; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Utility/_AutoMapper/CustomAutoMapperProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MyBlog.Model; 3 | using MyBlog.Model.DTO; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace MyBlog.WebApi.Utility._AutoMapper 10 | { 11 | 12 | public class CustomAutoMapperProfile : Profile 13 | { 14 | public CustomAutoMapperProfile() 15 | { 16 | base.CreateMap(); 17 | base.CreateMap() 18 | .ForMember(dest => dest.TypeName, sourse => sourse.MapFrom(src => src.TypeInfo.Name)) 19 | .ForMember(dest => dest.WriterName, sourse => sourse.MapFrom(src => src.WriterInfo.Name)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /MyBlog.WebApi/Utility/_MD5/MD5Helper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Cryptography; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace MyBlog.WebApi.Utility._MD5 9 | { 10 | public static class MD5Helper 11 | { 12 | public static string MD5Encrypt32(string password) 13 | { 14 | string pwd = ""; 15 | MD5 md5 = MD5.Create(); 16 | byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); 17 | for (int i = 0; i < s.Length; i++) 18 | { 19 | pwd = pwd + s[i].ToString("X"); 20 | } 21 | return pwd; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /MyBlog.WebApi/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MyBlog.WebApi 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /MyBlog.WebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /MyBlog.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "SqlConn": "Server=.;Database=MyBlogDB;Trusted_Connection=True;" 11 | } 12 | -------------------------------------------------------------------------------- /MyBlog.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30907.101 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyBlog.WebApi", "MyBlog.WebApi\MyBlog.WebApi.csproj", "{F7C07393-123A-4196-B0CF-B7B4CA3559A5}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyBlog.Model", "MyBlog.Model\MyBlog.Model.csproj", "{724C83DE-E1BA-4CD9-BC99-23C9B82A563E}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Repository", "Repository", "{A6652226-190D-4D7F-A239-BA7AF9DC3632}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Service", "Service", "{55E4BF0D-5588-4505-95C9-C540FE9EBDC5}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyBlog.IRepository", "MyBlog.IRepository\MyBlog.IRepository.csproj", "{6F78DED3-EE81-404D-90B7-742E127AC799}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyBlog.Repository", "MyBlog.Repository\MyBlog.Repository.csproj", "{794A657C-CB44-46BC-B294-19DE9BB7E479}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyBlog.IService", "MyBlog.IService\MyBlog.IService.csproj", "{12DFC07F-574B-43DD-B8CB-FDD13F33FEE6}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyBlog.Service", "MyBlog.Service\MyBlog.Service.csproj", "{111E6051-4AB7-4193-9180-D4DECF3A2201}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyBlog.JWT", "MyBlog.JWT\MyBlog.JWT.csproj", "{E35BDC8C-96E4-4398-B765-DFDBFF4ADB4D}" 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {F7C07393-123A-4196-B0CF-B7B4CA3559A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {F7C07393-123A-4196-B0CF-B7B4CA3559A5}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {F7C07393-123A-4196-B0CF-B7B4CA3559A5}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {F7C07393-123A-4196-B0CF-B7B4CA3559A5}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {724C83DE-E1BA-4CD9-BC99-23C9B82A563E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {724C83DE-E1BA-4CD9-BC99-23C9B82A563E}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {724C83DE-E1BA-4CD9-BC99-23C9B82A563E}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {724C83DE-E1BA-4CD9-BC99-23C9B82A563E}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {6F78DED3-EE81-404D-90B7-742E127AC799}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {6F78DED3-EE81-404D-90B7-742E127AC799}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {6F78DED3-EE81-404D-90B7-742E127AC799}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {6F78DED3-EE81-404D-90B7-742E127AC799}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {794A657C-CB44-46BC-B294-19DE9BB7E479}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {794A657C-CB44-46BC-B294-19DE9BB7E479}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {794A657C-CB44-46BC-B294-19DE9BB7E479}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {794A657C-CB44-46BC-B294-19DE9BB7E479}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {12DFC07F-574B-43DD-B8CB-FDD13F33FEE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {12DFC07F-574B-43DD-B8CB-FDD13F33FEE6}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {12DFC07F-574B-43DD-B8CB-FDD13F33FEE6}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {12DFC07F-574B-43DD-B8CB-FDD13F33FEE6}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {111E6051-4AB7-4193-9180-D4DECF3A2201}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {111E6051-4AB7-4193-9180-D4DECF3A2201}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {111E6051-4AB7-4193-9180-D4DECF3A2201}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {111E6051-4AB7-4193-9180-D4DECF3A2201}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {E35BDC8C-96E4-4398-B765-DFDBFF4ADB4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {E35BDC8C-96E4-4398-B765-DFDBFF4ADB4D}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {E35BDC8C-96E4-4398-B765-DFDBFF4ADB4D}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {E35BDC8C-96E4-4398-B765-DFDBFF4ADB4D}.Release|Any CPU.Build.0 = Release|Any CPU 58 | EndGlobalSection 59 | GlobalSection(SolutionProperties) = preSolution 60 | HideSolutionNode = FALSE 61 | EndGlobalSection 62 | GlobalSection(NestedProjects) = preSolution 63 | {6F78DED3-EE81-404D-90B7-742E127AC799} = {A6652226-190D-4D7F-A239-BA7AF9DC3632} 64 | {794A657C-CB44-46BC-B294-19DE9BB7E479} = {A6652226-190D-4D7F-A239-BA7AF9DC3632} 65 | {12DFC07F-574B-43DD-B8CB-FDD13F33FEE6} = {55E4BF0D-5588-4505-95C9-C540FE9EBDC5} 66 | {111E6051-4AB7-4193-9180-D4DECF3A2201} = {55E4BF0D-5588-4505-95C9-C540FE9EBDC5} 67 | EndGlobalSection 68 | GlobalSection(ExtensibilityGlobals) = postSolution 69 | SolutionGuid = {31AEC3BC-2DDC-4723-A34E-B8C3594DACB9} 70 | EndGlobalSection 71 | EndGlobal 72 | -------------------------------------------------------------------------------- /asp.net core个人博客.md: -------------------------------------------------------------------------------- 1 | # 1.概述 2 | 3 | ## 为啥要做这个项目? 4 | 5 | 我发现刚接触.net的开发者入门的话比较困难,没有适中的项目拿来练手,而且我看B站上也没有几个asp.netcore的项目,所以我想着做一个比较简单,通俗易懂的个人博客项目,很简单的增删改查,让刚接触.net的开发者更好学习asp.net core,这个项目我准备用asp.net core webapi+elementui来做,虽然这个项目很简单,但是麻雀虽小但五脏俱全,我还会用一些比较常用的架构来设计这个项目。每期视频我都会尽量按照10-20分钟左右时间来录制,可以更好的接受新知识 6 | 7 | # 2.数据库设计 8 | 9 | 文章表 10 | 11 | ```sql 12 | ID 13 | 文章标题 14 | 文章内容 15 | 创建时间 16 | 文章类型ID 17 | 浏览量 18 | 点赞量 19 | 作者ID 20 | ``` 21 | 22 | 文章类型表 23 | 24 | ```sql 25 | ID 26 | 类型名 27 | ``` 28 | 29 | 作者表 30 | 31 | ```sql 32 | ID 33 | 姓名 34 | 账号 35 | 密码 MD5 36 | ``` 37 | 38 | # 3.架构设计 39 | 40 | 仓储层 41 | 42 | 服务层 43 | 44 | # MD5加密 45 | 46 | ```C# 47 | public static string MD5Encrypt32(string password) 48 | { 49 | string pwd = ""; 50 | MD5 md5 = MD5.Create(); //实例化一个md5对像 51 | byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); 52 | for (int i = 0; i < s.Length; i++) 53 | { 54 | pwd = pwd + s[i].ToString("X"); 55 | } 56 | return pwd; 57 | } 58 | ``` 59 | 60 | # JWT使用 61 | 62 | ## JWT授权 63 | 64 | 1.添加一个webapi项目 65 | 66 | 2.安装Nuget程序包 System.IdentityModel.Tokens.Jwt 67 | 68 | ```C# 69 | var claims = new Claim[] 70 | { 71 | new Claim(ClaimTypes.Name, "张三") 72 | }; 73 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")); 74 | //issuer代表颁发Token的Web应用程序,audience是Token的受理者 75 | var token = new JwtSecurityToken( 76 | issuer: "http://localhost:6060", 77 | audience: "http://localhost:5000", 78 | claims: claims, 79 | notBefore: DateTime.Now, 80 | expires: DateTime.Now.AddHours(1), 81 | signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) 82 | ); 83 | var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); 84 | return jwtToken; 85 | ``` 86 | 87 | ## JWT鉴权 88 | 89 | 安装Microsoft.AspNetCore.Authentication.JwtBearer 90 | 91 | ```C# 92 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 93 | .AddJwtBearer(options => 94 | { 95 | options.TokenValidationParameters = new TokenValidationParameters 96 | { 97 | ValidateIssuerSigningKey = true, 98 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")), 99 | ValidateIssuer = true, 100 | ValidIssuer = "http://localhost:6060", 101 | ValidateAudience = true, 102 | ValidAudience = "http://localhost:5000", 103 | ValidateLifetime = true, 104 | ClockSkew = TimeSpan.FromMinutes(60) 105 | }; 106 | }); 107 | ``` 108 | 109 | ## JWT授权鉴权使用 110 | 111 | Swagger想要使用鉴权需要注册服务的时候添加以下代码 112 | 113 | ```C# 114 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 115 | { 116 | In=ParameterLocation.Header, 117 | Type=SecuritySchemeType.ApiKey, 118 | Description= "直接在下框中输入Bearer {token}(注意两者之间是一个空格)", 119 | Name="Authorization", 120 | BearerFormat="JWT", 121 | Scheme="Bearer" 122 | }); 123 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 124 | { 125 | { 126 | new OpenApiSecurityScheme 127 | { 128 | Reference=new OpenApiReference 129 | { 130 | Type=ReferenceType.SecurityScheme, 131 | Id="Bearer" 132 | } 133 | }, 134 | new string[] {} 135 | } 136 | }); 137 | ``` 138 | 139 | # AutoMapper 140 | 141 | 安装Nuget AutoMapper.Extensions.Microsoft.DependencyInjection 142 | 143 | 定义一个类,继承Profile 144 | 145 | ```C# 146 | public class CustomAutoMapperProfile:Profile 147 | { 148 | public CustomAutoMapperProfile() 149 | { 150 | base.CreateMap(); 151 | } 152 | } 153 | ``` 154 | 155 | 在服务中注册 156 | 157 | ```C# 158 | services.AddAutoMapper(typeof(CustomAutoMapperProfile)); 159 | ``` 160 | 161 | 构造函数注入 162 | 163 | ```C# 164 | private readonly IMapper _mapper; 165 | 166 | public StudentsController(IMapper mapper) 167 | { 168 | this._mapper = mapper; 169 | } 170 | ``` 171 | 172 | 复杂映射 173 | 174 | ```C# 175 | base.CreateMap() 176 | .ForMember(dest => dest.RoleMsg, sourse => sourse.MapFrom(src => src.RoleInfo.RoleMsg)); 177 | ``` 178 | 179 | ```C# 180 | User: 181 | UserPwd ->不能返回到前端 182 | UserName ->返回到前端 183 | UserDTO: 184 | UserName 185 | 186 | ``` 187 | 188 | --------------------------------------------------------------------------------