• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.net core模块学习

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、配置管理

二、管道

三、认证与授权

四、MVCDemo

五、IdentityServer4

 

 

一、配置管理

1,读取内存配置

using System;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>() {
                { "name","hunter"},
                { "age","10"}
            };

            var builder = new ConfigurationBuilder()
                .AddInMemoryCollection(dic)//当age没有值的时候使用dic里面的值
                .AddCommandLine(args);

            var configuration = builder.Build();

            Console.WriteLine($"name:{configuration["name"]}");
            Console.WriteLine($"age:{configuration["age"]}");

            Console.ReadKey();
        }
    }
}
demo

2,读取json文件

using System;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("class.json");

            var configuration = builder.Build();

            Console.WriteLine($"no:{configuration["no"]}");
            Console.WriteLine($"name:{configuration["name"]}");
            Console.WriteLine("student:");
            Console.WriteLine($"no:{configuration["student:0:no"]},name:{configuration["student:0:name"]}");
            Console.WriteLine($"no:{configuration["student:1:no"]},name:{configuration["student:1:name"]}");

            Console.ReadKey();
        }
    }
}
demo
{
  "no": "1",
  "name": "asp.net core",
  "student": [
    {
      "no": "1",
      "name": "张三"
    },
    {
      "no": "2",
      "name": "张三"
    }
  ]
}
class.json

3,读取appsettings.json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private IConfiguration _configuration;
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IActionResult Index()
        {
            Class c = new Class();
            _configuration.Bind(c);

            return View();
        }
    }
}
构造注入iconfiguration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
    public class Class
    {
        public string no { get; set; }
        public string name { get; set; }
        public IEnumerable<student> student { get; set; }
    }

    public class student {
        public string no { get; set; }
        public string name { get; set; }
    }
}
Class类
{
  "no": "1",
  "name": "asp.net core",
  "student": [
    {
      "no": "1",
      "name": "张三"
    },
    {
      "no": "2",
      "name": "张三"
    }
  ]
}
appsettings.json

 

二、管道

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.Extensions.Configuration;
 8 using Microsoft.Extensions.DependencyInjection;
 9 using Microsoft.AspNetCore.Http;
10 
11 namespace test2
12 {
13     public class Startup
14     {
15         public Startup(IConfiguration configuration)
16         {
17             Configuration = configuration;
18         }
19 
20         public IConfiguration Configuration { get; }
21 
22         // This method gets called by the runtime. Use this method to add services to the container.
23         public void ConfigureServices(IServiceCollection services)
24         {
25             services.AddMvc();
26         }
27 
28         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
29         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
30         {
31             if (env.IsDevelopment())
32             {
33                 app.UseDeveloperExceptionPage();
34             }
35             else
36             {
37                 app.UseExceptionHandler("/Home/Error");
38             }
39 
40             //管道被截断 url:http://ip:port/test
41             app.Map("/test",testApp=>{
42                 testApp.Run(async(context)=>{
43                     await context.Response.WriteAsync("test");
44                 });
45             });
46 
47             //管道插入
48             app.Use(async (context,next)=>{
49                 await context.Response.WriteAsync("1");
50                 await next.Invoke();
51             });
52 
53             //管道插入
54             app.Use(next=>{
55                 return (context)=>{
56                     return context.Response.WriteAsync("2");
57                 };
58             });
59 
60            
61             app.UseStaticFiles();
62 
63             app.UseMvc(routes =>
64             {
65                 routes.MapRoute(
66                     name: "default",
67                     template: "{controller=Home}/{action=Index}/{id?}");
68             });
69         }
70     }
71 }
Startup

1,模拟RequestDelegete

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace test3
{
    class Program
    {
        public static List<Func<RequestDelegete,RequestDelegete>> _list=new List<Func<RequestDelegete, RequestDelegete>>();
        static void Main(string[] args)
        {
            Use(next=>{
                return (context)=>{
                    Console.WriteLine(1);
                    return Task.CompletedTask;
                    //return next.Invoke(context);
                };
            });

            Use(next=>{
                return (context)=>{
                    Console.WriteLine(2);
                    return next.Invoke(context);
                };
            });

            RequestDelegete end=(context)=>{
                Console.WriteLine("end");
                return Task.CompletedTask;};
            
            _list.Reverse();
            foreach(var item in _list)
            {
                end=item.Invoke(end);
            }
            end.Invoke(new Context());

            Console.ReadKey();
        }

        public static void Use(Func<RequestDelegete,RequestDelegete> func)
        {
            _list.Add(func);
        }

    }
}
Program
using System;
using System.Threading.Tasks;

namespace test3
{
        public delegate Task RequestDelegete(Context context);
}
RequestDelegete
namespace test3
{
    public class Context
    {
        
    }
}
Context

 

三、认证与授权

1,Cookie-based认证

①注册Cookie认证

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;


namespace cookieBased
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //注册
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(option=>{
                        option.LoginPath="/Login/Index";
                    });

            services.AddMvc();
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            //添加认证中间件
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
Startup

②实现登录与注销

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using cookieBased.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

namespace cookieBased.Controllers
{
    public class LoginController:Controller
    {
        [HttpGet]
        public IActionResult Index(string returnUrl)
        {
            ViewData["returnUrl"]=returnUrl;
            return View();
        }

        [HttpPost]
        public IActionResult LoginIn(string returnUrl)
        {
            ClaimsIdentity identity=new ClaimsIdentity (new List<Claim>(){
                new Claim(ClaimTypes.Name,"hunter"),
                new Claim(ClaimTypes.Role,"admin")
            },CookieAuthenticationDefaults.AuthenticationScheme);
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity));

            var user= HttpContext.User.Identity.Name;
            var b= HttpContext.User.Identity.IsAuthenticated;

            return Redirect(returnUrl);
        }

        [HttpPost]
        public IActionResult LoginOut()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Redirect("/");
        }

    }
}
LoginController

案例下载:https://pan.baidu.com/s/15etE9CNfzDLCHW6ZHc-euw

 

2,JWT认证

jwt验证网站: https://jwt.io/

namespace JwtAuthenticate.Models
{
    public class JwtSettings
    {
        //token是谁颁发的
        public string Issure{get;set;}
        //可以给那些客户端使用
        public string Audience{get;set;}
        //需要加密的Secretkey
        public string Secretkey{get;set;}
    }
}
JwtAuthenticate.Models.JwtSettings
{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "JwtSettings":{
    "Audience":"http://localhost:5000",
    "Issure":"http://localhost:5000",
    "SecretKey":"11111111111111111"
  }
}
appsettings.json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using JwtAuthenticate.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace JwtAuthenticate
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //将配置文件jwtSettings注册进来
            //public AuthorizeController(IOptions<JwtSettings> jwtSettings)会使用到
            services.Configure<JwtSettings>(Configuration.GetSection("jwtSettings"));

            var jwtSettings=new JwtSettings();
            Configuration.Bind("JwtSettings",jwtSettings);
            
            services.AddAuthentication(options=>{//配置Authentication
                options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options=>{//配置JwtBearer
                options.TokenValidationParameters=new TokenValidationParameters{
                    ValidIssuer=jwtSettings.Issure,
                    ValidAudience=jwtSettings.Audience,
                    IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secretkey))
                };
            });

            services.AddMvc();
        }

        // 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.UseAuthentication();
            app.UseMvc();
        }
    }
}
Startup
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JwtAuthenticate.Models;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;

namespace JwtAuthenticate.Controllers
{

    [Route("api/[controller]")]
    public class AuthorizeController:Controller
    {
        private JwtSettings _jwtSettings;
        public AuthorizeController(IOptions<JwtSettings> jwtSettings)
        {
            _jwtSettings=jwtSettings.Value;
        }

        [HttpGet]
        public string A()
        {
            return "a";
        }

        [HttpPost]
        public IActionResult Token([FromBody]LoginViewModel model)
        {
            if(!ModelState.IsValid)return BadRequest();
            if(!(model.UserName=="hunter"&&model.Password=="123456"))return BadRequest();
            
            var claims=new Claim[]{
                new Claim(ClaimTypes.Name,"hunter"),
                new Claim(ClaimTypes.Role,"admin")
            };

            var key=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Secretkey));
            var creds=new SigningCredentials(key,SecurityAlgorithms.HmacSha256);
            var token=new JwtSecurityToken(
                _jwtSettings.Issure
                ,_jwtSettings.Audience
                ,claims,DateTime.Now,DateTime.Now.AddMinutes(30)
                ,creds);
            return Ok(new {token=new JwtSecurityTokenHandler().WriteToken(token)});
        }
        
    }
}
AuthorizeController

 

3,基于Claim的Jwt认证

①加上authorize标签

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace JwtAuthenticate.Controllers
{

    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
    
        [Authorize(Policy="values.Get")]
        
        // GET api/values
        [HttpGet] 
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

         [Authorize(Policy="values.Get")]
        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        [Authorize(Policy="values.Post")]
        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        [Authorize(Policy=" 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap