AOP explanation of .netcore (3)

Get into the habit of writing together! This is the 8th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

foreword

Today, I will continue to explain the AOP of .netcore. Without further ado, let's take a look.

ExceptionFilter extension

Contains multiple implementations of IExceptionFilter and IAsyncExceptionFilter

Start extended customization

The execution characteristics of synchronous exceptions---if the abstract parent class of ActionFilterAttribute is implemented, only the asynchronous version of the method will be executed during execution---it is directly judged in the source code. If there is an asynchronous version, the synchronous version will not be executed.

ExceptionFilter package extension landing

Standard handling of exceptions

Return different data according to the situation

//CustomExceptiionFilter.cs
​
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
​
namespace 练习Demo.Unity.Filter
{
    public class CustomExceptiionFilter : Attribute, IExceptionFilter
    {
​
        private readonly IModelMetadataProvider _ModelMetadataProvider;
        public CustomExceptiionFilter(IModelMetadataProvider ModelMetadataProvider)
        {
            this._ModelMetadataProvider = ModelMetadataProvider;
        }
        public void OnException(ExceptionContext context)
        {
            //这里进行异常处理或者将响应结果给客户端
            //给客户端有两种形式
            //1.页面展示
            //2.包装成JSON格式
​
            if (IsAjaxRequest(context.HttpContext.Request))  //判断是否为Ajax请求,
            {
                context.Result = new JsonResult(
                    new
                    {
                        Success = false,
                        Message = context.Exception.Message,
                    }
               );
​
            }
            else
            {
                ViewResult result = new ViewResult { ViewName = "/Views/Shared/Error.cshtml" };
​
                result.ViewData = new ViewDataDictionary(_ModelMetadataProvider, context.ModelState);
​
                result.ViewData.Add("Excption",context.Exception);
                context.Result = result;  //断路器  --只要给context.Result赋值了,就不会往后执行了
​
            }
        }
​
​
​
        private bool IsAjaxRequest(HttpRequest request)
        {
            string header = request.Headers["X-Requested-With"];
            return "XMLHttpRequest".Equals(header);
        }
    }
}
​
​
​
//ExcepitonFController.cs
​
using Microsoft.AspNetCore.Mvc;
using 练习Demo.Unity.Filter;
​
namespace 练习Demo.Controllers
{
    public class ExcepitonFController : Controller
    {
        [TypeFilter(typeof(CustomExceptiionFilter))]
        public IActionResult Index()
        {
            throw new Exception("抛出异常");
        }
    }
}
​
​
​
//Error.cshtml
​
@model ErrorViewModel
@{
   
    Exception exception = ViewData["Excption"] as Exception;
}
​
<h1 class="text-danger">Error.</h1>
@if(exception != null)
{
<h1 class="text-danger">@exception.Message</h1>    
}
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h2>大家好</h2>
​

复制代码

Scenario analysis of exception handling

Action throws an unhandled exception

Action has handled exception

Service layer exception

An exception occurred when the View was bound

Url address that does not exist

Exceptions that occur in other Filters

For example: ActionFilter exception can be caught

Resource, ResultFilter can not capture

Controller constructor throws exception

Exception handling not caught by ExceptionFilter

Middleware support

//program.cs
//如果HTTp请求中的Response中的状态不是200,就会进入Home/Error中
app.UseStateCodePagesWithReExcute("/Home/Error/{0}")
​
    
    
//下面拼装一个Response输出
 app.UseExceptionHandler(erroAPP=>{
     。
 })
​
复制代码

Comprehensive support catches all exceptions

ExceptionFilter+middleware== handle all exceptions

Authentication and authorization

Authorization Background Introduction

Http protocol stateless Cookies+Session authorization basic configuration

Basic configuration of ASP.NETCore traditional authorization

Use middleware

Configure the authorization process

Authorization takes effect

Code:

//program.cs
  
//授权配置
builder.Services.AddAuthentication(option =>
{
    option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    option.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    option.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,option =>
{
    option.LoginPath = "/userloginAuten/login";   //如果没有获取到用户信息,鉴权失败,授权自然也失败,跳转到指定的Action
});
​
​
//使用中间件
app.UseAuthorization();  //鉴权
app.UseAuthorization();   //授权
​
​
​
​
//UserloginAutenController.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
​
namespace 练习Demo.Controllers
{
    public class UserloginAutenController : Controller
    {
        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
​
​
​
        public IActionResult Login()
        {
            return View();
        }
​
​
        [HttpPost]
        public async Task<IActionResult> login(string name, string password)
        {
​
            var claims = new List<Claim>()
                    {    new Claim("useid","1"),
                        new Claim(ClaimTypes.Role, "Admin"),
                        new Claim(ClaimTypes.Role, "User"),
                    };
​
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
            });
​
            var user = HttpContext.User;
            return base.Redirect("/userloginAuten/Index");
​
​
        }
​
    }
}
​
​
//login.cshtml
​
​
    @*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
​
<h2>登录</h2>
@*<section>*@
   @* @using (Html.BeginForm("login","userloginAuten",new {sid="123",Accout="111"},
     FormMethod.Post,true,new {@class="form-horizontal",role="form"}
    ))
​
    {
        @Html.AntiForgeryToken()
        <hr/>
        @Html
        ValidationSummary(true);
​
        <div>
             @Html.LabelFor(m=>m.Name, new {@class = "col-sm-1"})
            <div>
                 @Html.TextBoxFor(m=>m.Name, new {@class = "form-control",@placeholder="请输入用户名"})
            </div>
​
        </div>
​
         <div>
             @Html.LabelFor(m=>m.Password, new {@class = "col-sm-1"})
            <div>
                 @Html.TextBoxFor(m=>m.Password, new {@class = "form-control",@placeholder="请输入密码"})
            </div>   
        </div>
​
​
        <div><button type="submit">登录</button></div>
        @base.ViewBag.msg
​
​
    }
​
​
</section>*@
复制代码

Summary: Still the same sentence, step by step, come on!

Guess you like

Origin juejin.im/post/7084978556681322533
AOP
Recommended