ASP.NET Core MVC 2.x 全面教程 笔记

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<IWelcomService, WelcomService>();
            //每次方法请求这个参数的时候都建立新实例
            services.AddTransient<IWelcomService, WelcomService>();
            //每次web请求会生成一个实例,在这个web请求期间如果多次请求那么还是使用同一个实例
            services.AddScoped<IWelcomService, WelcomService>();
        }

        // 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. 中间件

        /// <summary>
        /// 配置web请求中间件(只执行一次)
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="welcomService"></param>
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IWelcomService welcomService,
            ILogger<Startup> 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)
{
<li>@s.Name (@s.Age) <a href="/Home/Detail/@s.Id">Detail</a></li>
@Html.ActionLink("明细","Detail",new {id=s.id});
<a asp-action="Detail" asp-route-id="@s.Id">明细Tag</a>
}

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

Db

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(DbContextOptions<DataContext>options)
            :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<DataContext>(options=> { options.UseSqlServer(connectionString)});
            
        }

        /// <summary>
        /// 配置web请求中间件(只执行一次)
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="welcomService"></param>
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IWelcomService welcomService,
            ILogger<Startup> 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 下

@Component.InvokeAsync()与@Html.Partial()

 如果使用<vc></vc>需要引入项目程序集命名空间

如果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

CSS 

ASP.NET Core MVC 14. ASP.NET Core Identity 入门

UserManager<IdentityUser>

SignInManager<IdentityUser>

 

或者ApplicationDbContext

cshtml调用SignInManager

@using Microsoft.AspNetCore.Identity

@inject SignInManager<IdentityUser>SignInManager

@if(SignInManager.IsSignedIn(User))

{

<a>退出</a>

}

else{

<a>登录</a>

}

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<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;

        public RoleController(
            UserManager<ApplicationUser> userManager,
            RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }

        public async Task<IActionResult> Index()
        {
            var roles = await _roleManager.Roles.ToListAsync();
            return View(roles);
        }

        public IActionResult AddRole()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> 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<IActionResult> 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<string>()
            };

            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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值