ASP.NET Core MVC 01. 创建项目 +项目结构和配置简介
ASP.NET Core MVC 02. Web Host 的默认配置
ASP.NET Core MVC 03. 服务注册和管道
服务注册
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//单例模式 在整个web项目生命周期里只会有一个实例
services.AddSingleton();
//每次方法请求这个参数的时候都建立新实例
services.AddTransient();
//每次web请求会生成一个实例,在这个web请求期间如果多次请求那么还是使用同一个实例
services.AddScoped();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
POST/Product
比如有一个post请求Product
Logger可以查看所有请求进来的信息(请求路径,查询字符串,head,cookie,token)
Logger可以记录信息,改变信息,甚至可以拒绝请求
ASP.NET Core MVC 04. 中间件
///
/// 配置web请求中间件(只执行一次)
///
///
///
///
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IWelcomService welcomService,
ILogger logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
//app.Run不经常用,通常用app.Use
app.Use(next =>
{
//只输出一次
logger.LogInformation("app.Use.............");
return async httpContext =>
{
//每次请求都会运行
logger.LogInformation("----async httpContext");
if (httpContext.Request.Path.StartsWithSegments("/first"))
{
logger.LogInformation("----First");
await httpContext.Response.WriteAsync("First!!!");
}
else
{
logger.LogInformation("next(httpContext)");
await next(httpContext);
}
};
});
app.UseWelcomePage(new WelcomePageOptions
{
Path = "/welcome"
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
ASP.NET Core MVC 05.Controller 的路由
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
app.UseMvc(builder=> {
builder.MapRoute("Default","{controller}/{action}/{id?}");
});
app.UseMvc(builder=> {
builder.MapRoute("Default","{controller=Home}/{action=Index}/{id?}");
});
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Route("About")]
[Route("[controller]")]
[Route("[controller]/[action]")]
[Route("v2/[controller]/[action]")]
public class AboutController
{
[Route("")]
public string Me()
{
return "Dave";
}
[Route("company")]
[Route("[action]")]
public string Company()
{
return "No Company";
}
}
}
ASP.NET Core MVC 06. Controller 返回View
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
this.ControllerContext.ActionDescriptor.ControllerName = "";
this.ControllerContext.ActionDescriptor.ActionName = "";
return this.Ok();
return this.BadRequest();
return this.NotFound();
return new ObjectResult(new { a=""});
return View();
}
}
}
ASP.NET Core MVC 07. View的Model 和 Tag Helpers
@foreach(var s in Model.Students)
{
@s.Name (@s.Age) Detail
@Html.ActionLink("明细","Detail",new {id=s.id});
明细Tag
}
Tag需要引用 Microsoft.AspNetCore.Razor.Design
@addTagHelper *,Micrsoft.AspNetCore.Mvc.TagHelpers
ASP.NET Core MVC 08. 输入Model和防止重复Post
ASP.NET Core MVC 09. Model验证
ASP.NET Core MVC 10. 使用EF Core
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Data
{
public class DataContext:DbContext
{
//不是线程安全的,注入的时候一个请求一个实例
public DataContext(DbContextOptionsoptions)
:base(options)
{
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Waring"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WebApplication1.Data;
namespace WebApplication1
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connectionString = _configuration["ConnectionStrings:DefaultConnection"];
connectionString = _configuration.GetConnectionString("DefaultConnection");
services.AddDbContext(options=> { options.UseSqlServer(connectionString)});
}
///
/// 配置web请求中间件(只执行一次)
///
///
///
///
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IWelcomService welcomService,
ILogger logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
//app.Run不经常用,通常用app.Use
app.UseStaticFiles();
app.UseFileServer();
app.UseMvc(builder=> {
builder.MapRoute("Default","{controller=Home}/{action=Index}/{id?}");
});
app.Use(next =>
{
//只输出一次
logger.LogInformation("app.Use.............");
return async httpContext =>
{
//每次请求都会运行
logger.LogInformation("----async httpContext");
if (httpContext.Request.Path.StartsWithSegments("/first"))
{
logger.LogInformation("----First");
await httpContext.Response.WriteAsync("First!!!");
}
else
{
logger.LogInformation("next(httpContext)");
await next(httpContext);
}
};
});
app.UseWelcomePage(new WelcomePageOptions
{
Path = "/welcome"
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
ASP.NET Core MVC 11. Views 上
ASP.NET Core MVC 12. Views 下
如果WelcomeViewComponent是WelcomeStudentsViewComponent,按照下面的写法
ASP.NET Core MVC 13. 安装前端库
package.json
{
"version": "1.0.0",
"name": "webapplication1",
"private": true,
"devDependencies": {},
"dependencies": {
"bootstrap": "3.3.7"
}
}
开发环境用本地js生成环境用cdn
ASP.NET Core MVC 14. ASP.NET Core Identity 入门
或者ApplicationDbContext
cshtml调用SignInManager
@using Microsoft.AspNetCore.Identity
@inject SignInManager
@if(SignInManager.IsSignedIn(User))
{
}
else{
}
stratup.cs里的Configure方法下添加app.UseAuthentication();
ASP.NET Core MVC 15. 用户管理
对IdentityUser扩展可以新建一个类,继承 IdentityUser
ASP.NET Core MVC 16. 角色管理
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Heavy.Web.Models;
using Heavy.Web.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Heavy.Web.Controllers
{
[Authorize]
public class RoleController : Controller
{
private readonly UserManager _userManager;
private readonly RoleManager _roleManager;
public RoleController(
UserManager userManager,
RoleManager roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
public async Task Index()
{
var roles = await _roleManager.Roles.ToListAsync();
return View(roles);
}
public IActionResult AddRole()
{
return View();
}
[HttpPost]
public async Task AddRole(RoleAddViewModel roleAddViewModel)
{
if (!ModelState.IsValid)
{
return View(roleAddViewModel);
}
var role = new IdentityRole
{
Name = roleAddViewModel.RoleName
};
var result = await _roleManager.CreateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(roleAddViewModel);
}
public async Task EditRole(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null)
{
return RedirectToAction("Index");
}
var roleEditViewModel = new RoleEditViewModel
{
Id = id,
RoleName = role.Name,
Users = new List()
};
var users = await _userManager.Users.ToListAsync();
foreach (var user in users)
{
if (await _userManager.IsInRoleAsync(user, role.Name))
{
roleEditViewModel.Users.Add(user.UserName);
}
}
return View(roleEditViewModel);
}
[HttpPost]
public async Task EditRole(RoleEditViewModel roleEditViewModel)
{
var role = await _roleManager.FindByIdAsync(roleEditViewModel.Id);
if (role != null)
{
role.Name = roleEditViewModel.RoleName;
var result = await _roleManager.UpdateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
ModelState.AddModelError(string.Empty, "更新角色时出错");
return View(roleEditViewModel);
}
return RedirectToAction("Index");
}
[HttpPost]
public async Task DeleteRole(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role != null)
{
var result = await _roleManager.DeleteAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
ModelState.AddModelError(string.Empty, "删除角色时出错");
}
ModelState.AddModelError(string.Empty, "没找到该角色");
return View("Index", await _roleManager.Roles.ToListAsync());
}
public async Task AddUserToRole(string roleId)
{
var role = await _roleManager.FindByIdAsync(roleId);
if (role == null)
{
return RedirectToAction("Index");
}
var vm = new UserRoleViewModel
{
RoleId = role.Id
};
var users = await _userManager.Users.ToListAsync();
foreach (var user in users)
{
if (!await _userManager.IsInRoleAsync(user, role.Name))
{
vm.Users.Add(user);
}
}
return View(vm);
}
[HttpPost]
public async Task AddUserToRole(UserRoleViewModel userRoleViewModel)
{
var user = await _userManager.FindByIdAsync(userRoleViewModel.UserId);
var role = await _roleManager.FindByIdAsync(userRoleViewModel.RoleId);
if (user != null && role != null)
{
var result = await _userManager.AddToRoleAsync(user, role.Name);
if (result.Succeeded)
{
return RedirectToAction("EditRole", new { id = role.Id });
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(userRoleViewModel);
}
ModelState.AddModelError(string.Empty, "用户或角色未找到");
return View(userRoleViewModel);
}
public async Task DeleteUserFromRole(string roleId)
{
var role = await _roleManager.FindByIdAsync(roleId);
if (role == null)
{
return RedirectToAction("Index");
}
var vm = new UserRoleViewModel
{
RoleId = role.Id
};
var users = await _userManager.Users.ToListAsync();
foreach (var user in users)
{
if (await _userManager.IsInRoleAsync(user, role.Name))
{
vm.Users.Add(user);
}
}
return View(vm);
}
[HttpPost]
public async Task DeleteUserFromRole(UserRoleViewModel userRoleViewModel)
{
var user = await _userManager.FindByIdAsync(userRoleViewModel.UserId);
var role = await _roleManager.FindByIdAsync(userRoleViewModel.RoleId);
if (user != null && role != null)
{
if (await _userManager.IsInRoleAsync(user, role.Name))
{
var result = await _userManager.RemoveFromRoleAsync(user, role.Name);
if (result.Succeeded)
{
return RedirectToAction("EditRole", new { id = role.Id });
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(userRoleViewModel);
}
ModelState.AddModelError(string.Empty, "用户不在角色里");
return View(userRoleViewModel);
}
ModelState.AddModelError(string.Empty, "用户或角色未找到");
return View(userRoleViewModel);
}
}
}
ASP.NET Core MVC 17. 基于Claim和Policy的授权 上
services.AddAuthorization(options =>
{
options.AddPolicy("仅限管理员", policy => policy.RequireRole("Administrators"));
options.AddPolicy("编辑专辑", policy=> policy.RequireClaim("Edit Albums"));
});
[Authorize(Policy = "编辑专辑")]
public class AlbumController : Controller
{
[Authorize(Roles = "Administrators")]
public class UserController : Controller
{
ASP.NET Core MVC 18. 基于Claim和Policy的授权 下 - 自定义Policy
services.AddAuthorization(options =>
{
options.AddPolicy("仅限管理员", policy => policy.RequireRole("Administrators"));
options.AddPolicy("编辑专辑", policy => policy.RequireClaim("Edit Albums"));
options.AddPolicy("编辑专辑1", policy => policy.RequireAssertion(context =>
{
if (context.User.HasClaim(x => x.Type == "Edit Albums"))
return true;
return false;
}));
options.AddPolicy("编辑专辑2", policy => policy.AddRequirements(
// new EmailRequirement("@126.com"),
new QualifiedUserRequirement()));
});
ASP.NET Core MVC 19. XSS & CSRF
ASP.NET Core MVC 20. Model Binding
ASP.NET Core MVC 21. Model 验证 Again
ASP.NET Core MVC 22. 再讲Tag Helpers
ASP.NET Core MVC 23. 继续讲Tag Helpers 和复习View Component
ASP.NET Core MVC 24. Logging
ASP.NET Core MVC 25. 过滤器
ASP.NET Core MVC 26. 缓存
ASP.NET Core MVC 27. CICD Azure DevOps