Core知识整理

概述

Commond-Line

ASP.NET结构文件

 

Startup

配置文件

 

中间件和依赖注入

依赖注入原理

框架自带的依赖注入(IServiceCollection)

依赖注入生命周期

依赖注入使用方式

  • 通过构造函数
  • MVC的ActionAction中可以使用 [FromServices]来注入对象、

中间件(MiddleWare)

Use:进入中间件http管道模式,

Map:映射分支 Run:

执行,并返回Response

复制代码
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     app.UseMyMiddleware();
}

public class MyMiddleware
    {
        private readonly RequestDelegate _next;
        public MyMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public Task Invoke(HttpContext context)
        {
           //这里是获取context信息后处理的代码
            return this._next(context);
        }
    }
    public static class MyMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyMiddleware(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddlewareMiddleware>();
        }
    }
复制代码

 

中间件的执行要注意顺序,因为可以终止http管道的执行

框架自带中间件

 

 ORM

Entity Framework Core

官方地址:https://docs.microsoft.com/zh-cn/ef/core/

services.AddDbContext<SchoolContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Entity Framework Core-Code First
//程序包管理控件台
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

 

从数据库生成模型
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
并发控制
复制代码
//特性方式
public class Person
{
    public int PersonId { get; set; }

    [ConcurrencyCheck]
    public string LastName { get; set; }

    public string FirstName { get; set; }
}

//特性API方式

class MyContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .Property(p => p.LastName)
            .IsConcurrencyToken();
    }
}

public class Person
{
    public int PersonId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

//特性时间戳

public class Blog
{
    public int BlogId { get; set; }

    public string Url { get; set; }
    
    [Timestamp]
    public byte[] Timestamp { get; set; }
}

//时间戳 class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(p => p.Timestamp) .IsRowVersion(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public byte[] Timestamp { get; set; } }
复制代码

Dapper

官方地址:https://github.com/StackExchange/Dapper

 

权限验证

概念

Authentication:认证,通过自定义或三方的方式,确定用户有效性,并分配用户一定身份

Authorization:授权,决定用户可以做什么,可以带上角色或策略来授权,并且是能过Controller或Action上的特性Authorize来授权的。

验证方式

ConfigureServices中

复制代码
//注入验证 2.0
services.AddAuthentication(options =>
{
     options.DefaultChallengeScheme = "MyCookieAuthenticationScheme";
     options.DefaultSignInScheme = "MyCookieAuthenticationScheme";
     options.DefaultAuthenticateScheme = "MyCookieAuthenticationScheme";
})
.AddCookie("MyCookieAuthenticationScheme", opt =>
            {
     opt.LoginPath = new PathString("/login");
     opt.AccessDeniedPath = new PathString("/login");
     opt.LogoutPath = new PathString("/login");
     opt.Cookie.Path = "/";
});
复制代码

Configure中

app.UseAuthentication();
登录验证
复制代码
public class UserTestController : Controller  
{
      [HttpGet("users")]
      [Authorize(Roles = "admin,system")]
      public IActionResult Index()
      {     return View();      }
      [HttpGet("login")]
      public IActionResult Login(string returnUrl)
      {
          //1、如果登录用户已经Authenticated,提示请勿重复登录
          if (HttpContext.User.Identity.IsAuthenticated)
          {
              return View("Error", new string[] { "您已经登录!" });
          }else//记录转入地址
          {
                    ViewBag.returnUrl = returnUrl;
          return View();}
      }
复制代码

 

复制代码
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(string username, string returnUrl)
{
            //2、登录后设置验证
        if (username == "gsw")
        {
             var claims = new Claim[]{
                 new Claim(ClaimTypes.Role, "admin"),
                 new Claim(ClaimTypes.Name,"桂素伟")
             };
             HttpContext.SignInAsync("MyCookieAuthenticationScheme",new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookie")));              
                //给User赋值 
                var claPris = new ClaimsPrincipal();
                claPris.AddIdentity(new ClaimsIdentity(claims));
                HttpContext.User = claPris;
                return new RedirectResult(returnUrl == null ? "users" : returnUrl);
            }
            else
            {
                return View();
            }
        }
复制代码
UI访问
复制代码
//3、UI上访问验证信息
@if (User.IsInRole("abc"))
 {
     <p>你好: @User.Identity.Name</p>
     <a href="更高权限">更高权限</a>
 }
复制代码

 

权限中间件
复制代码
/// <summary>
    /// 权限中间件
    /// </summary>
    public class PermissionMiddleware
    {
        /// <summary>
        /// 管道代理对象
        /// </summary>
        private readonly RequestDelegate _next;

        /// <summary>
        /// 权限中间件构造
        /// </summary>
        /// <param name="next">管道代理对象</param>
        /// <param name="permissionResitory">权限仓储对象</param>
        /// <param name="option">权限中间件配置选项</param>
        public PermissionMiddleware(RequestDelegate next)
        {
         _next = next;
        }
        /// <summary>
        /// 调用管道
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext context)
        {
             return this._next(context);
        }
    }
复制代码
自定义策略
复制代码
/// <summary>
/// 权限授权Handler
/// </summary>
public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
     /// <summary>
     /// 用户权限
     /// </summary>
     public List<Permission> Permissions { get; set; }

     protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
     {
         //赋值用户权限
         Permissions = requirement.Permissions;
         //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
         var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
         //请求Url
         var questUrl = httpContext.Request.Path.Value.ToLower();
         //是否经过验证
         var isAuthenticated = httpContext.User.Identity.IsAuthenticated;
         if (isAuthenticated)
         {
             //权限中是否存在请求的url
             if (Permissions.GroupBy(g => g.Url).Where(w => w.Key.ToLower() == questUrl).Count() > 0)
             {
                 var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value;                   
                 //验证权限
                 if (Permissions.Where(w => w.Name == name && w.Url.ToLower() == questUrl).Count() > 0)
                 {
                     context.Succeed(requirement);
                 }
                 else
                 {
                     //无权限跳转到拒绝页面
                     httpContext.Response.Redirect(requirement.DeniedAction);
                 }
             }
             else
             {
                 context.Succeed(requirement);
             }
         }
         return Task.CompletedTask;
     }
 }
复制代码
 自定义策略-JWT
复制代码
 /// <summary>
 /// 权限授权Handler
 /// </summary>
 public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
 {
     /// <summary>
     /// 验证方案提供对象
     /// </summary>
     public IAuthenticationSchemeProvider Schemes { get; set; }
     /// <summary>
     /// 自定义策略参数
     /// </summary>
     public PermissionRequirement Requirement
     { get; set; }
     /// <summary>
     /// 构造
     /// </summary>
     /// <param name="schemes"></param>
     public PermissionHandler(IAuthenticationSchemeProvider schemes)
     {
         Schemes = schemes;
     }
     protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
     {          
         赋值用户权限       
         Requirement = requirement;
         //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
         var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
         //请求Url
         var questUrl = httpContext.Request.Path.Value.ToLower();
         //判断请求是否停止
         var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
         foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
         {
             var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;
             if (handler != null && await handler.HandleRequestAsync())
             {
                 context.Fail();
                 return;
             }
         }
         //判断请求是否拥有凭据,即有没有登录
         var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
         if (defaultAuthenticate != null)
         {
             var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);
             //result?.Principal不为空即登录成功
             if (result?.Principal != null)
             {                
                 httpContext.User = result.Principal;
                 //权限中是否存在请求的url
                 if (Requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key.ToLower() == questUrl).Count() > 0)
                 {
                     var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value;
                     //验证权限
                     if (Requirement.Permissions.Where(w => w.Name == name && w.Url.ToLower() == questUrl).Count() <= 0)
                     {
                         //无权限跳转到拒绝页面
                         httpContext.Response.Redirect(requirement.DeniedAction);
                     }
                 }
                 context.Succeed(requirement);
                 return;
             }
         }
         //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
         if (!questUrl.Equals(Requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST")
            || !httpContext.Request.HasFormContentType))
         {
             context.Fail();
             return;
         }
         context.Succeed(requirement);
     }
 }

转载于:https://www.cnblogs.com/Agui520/p/9428537.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UIKit是苹果公司为iOS和macOS平台提供的核心框架之一,主要用于构建用户界面和应用程序交互。以下是UIKit的基础知识概述: 1. **视图层次结构**: UIKit的设计基于树状的视图层次结构,从根视图开始,包含窗口(Window)、视图容器(View Controller)以及各种UI元素(如UILabel, UIButton, UIImageView等)。 2. **视图控件**: UIView是所有UI元素的基本组件,它可以设置位置、大小、背景颜色和约束。UIViewController负责管理视图,并可以响应用户事件。 3. **Auto Layout**: 自动布局系统帮助开发者轻松地处理不同屏幕尺寸下的布局调整,通过设置view之间的约束来保持布局的一致性。 4. **手势识别**: UIGestureRecognizer允许处理各种触屏手势,例如Tap、Pan、Swipe等,为增强用户体验提供便利。 5. **文本和图像显示**: UILabel用于显示文本,UIImageView则用于显示图片。还可以使用NSAttributedString和Core Graphics进行更复杂的文本和图形渲染。 6. **事件处理**: 通过代理方法或通知机制,开发者可以监听和响应用户的操作,如按钮点击、键盘事件等。 7. **动画和过渡**: 使用UIView.animate或CADisplayLink进行界面动画,以及UIStoryboardSegue进行界面跳转时的平滑过渡效果。 8. **用户界面自定义**: 可以通过KVC、KVO、NSCoding等方式定制视图属性,或通过自绘视图Custom Drawing来实现独特的UI效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值