ASP.NET CORE基础教程

目录
  • 第一课 基本概念
  • 第二课 控制器的介绍
  • 第三课 视图与表单
  • 第四课 数据验证
  • 第五课 路由规则
  • 第六课 应用发布与部署
  • 源码地址

第一课 基本概念

  • 基本概念

    • Asp.Net Core Mvc是.NET Core平台下的一种Web应用开发框架

      • 符合Web应用特点
      • .NET Core跨平台解决方案
      • MVC设计模式的一种实现
  • 环境准备

第二课 控制器的介绍

  • 控制器定义方式:

    • 命名以Controller结尾
    • 使用ControllerAttribute标注
    public class TestController : Controller
    {

    }

    [Controller]
    public class Test : Controller
    {

    }
  • 默认路由规则

    • 域名/控制器类/方法
    • {Domain}/{Controller}/{Action}
  • 数据形式
    • QueryString: ?name=zhangsan&age=22
    • Form
    • Cookie
    • Session
    • Header
  • HttpRequest
    • HttpRequest 是用户请求对象
    • 提供获取请求数据的属性
      • Cookies,Headers,Query,QueryString,Form
        public IActionResult Hello()
        {
            // Query
            var name = Request.Query["name"];
            // QueryString
            var query = Request.QueryString.Value;
            // Form
            var username = Request.Form["username"];
            // Cookies
            var cookie = Request.Cookies["item"];
            // Headers
            var headers = Request.Headers["salt"];

            return Content("Hello");
        }
  • HttpContext

    • HttpContext是用户请求上下文
    • 提供Session属性获取Session对象
      • Session.Set 设置
      • Session.Remove 移除
      • Session.TryGetValue 获取数据
        public IActionResult Hello()
        {
            // byte[]
            HttpContext.Session.Set("byte", new byte[] { 1, 2, 3, 4, 5 });
            var bytes = HttpContext.Session.Get("byte");
            // string
            HttpContext.Session.SetString("name", "tom");
            var name = HttpContext.Session.GetString("name");
            // int
            HttpContext.Session.SetInt32("id", 20);
            var id = HttpContext.Session.GetInt32("id");
            HttpContext.Session.Remove("name");
            HttpContext.Session.Clear();

            return Content("Hello");
        }
  • 数据绑定

    • 把用户请求的数据绑定到控制器方法的参数上
    • 支持简单类型与自定义类型
    • 绑定规则是请求数据名称与参数名称一致
      • 如查询字符串key名称跟参数一致
      • Form表单名称跟参数一致
        public IActionResult Hello(RequestModel request,int? age)
        {
            // 查询字符串
            var test = Request.Query["test"];
            // 简单类型
            var userAge = age;
            // 自定义类型
            var name = request.Name;

            return Content("Hello");
        }

        public class RequestModel
        {
            public string Name { get; set; }
        }
  • 内容补充

    • 如果以Controller结尾的都是控制器,那如果程序里面由一些业务命名的时候也是以Controller结尾,怎么办?
    • NonControllerAttribute
    /// <summary>
    /// 拍卖师控制类
    /// </summary>
    [NonController]
    public class AuctionController
    {

    }
  • 常用特性
特性 数据源
FromHeaderAttribute 请求头数据
FromRouteAttribute 路由数据
FromBodyAttribute 请求体
FromFormAttribute 表单数据
FromQueryAttribute 查询字符串
FromServicesAttribute 服务注册
        public IActionResult Say(
            [FromForm]string name,
            [FromQuery]int age,
            [FromHeader] string salt,
            [FromBody] string content
            )
        {
            return View();
        }
  • 特性参数

    • 通过特性修饰参数来影响绑定逻辑
    • 灵活扩展
  • IActionResult
    • 动作结果接口
    • 具体实现
      • JsonResult:返回JSON结构数据
      • RedirectResult:跳转到新地址
      • FileResult:返回文件
      • ViewResult:返回视图内容
      • ContentResult:文本内容

第三课 视图与表单

  • 数据传递

    • ViewData
    • ViewBag
    • tempData
    • Model
    • Session
    • Cache
ViewData ViewBag
键值对 动态类型
索引器 ViewData的封装
支持任意类型 动态属性
TempData Cache Session
视图级别 应用程序级别 会话级别
只允许消费一次 服务器端保存 服务器端保存
可多次赋值 可设置有效期 键值对形式
键值对形式 键值对形式  
  • Cache

    • 与.NET Framework时代不同,一种全新实现
    • IMemoryCache接口
    • 依赖注入方式获取
    • IMemoryCache.Get/Set操作数据
    [Controller]
    public class Test : Controller
    {
        private readonly IMemoryCache _cache;

        public Test(IMemoryCache memoryCache)
        {
            this._cache = memoryCache;
        }

        public IActionResult ReadCache()
        {
            _cache.Set("name","tom");
            _cache.Get("name");

            _cache.Set("age",30);
            _cache.Get("age");

            User tom = new User(){ Name = "admin",Pwd = "123456"};
            _cache.Set<User>("user",tom);
            _cache.Get<User>("user");
            return Content("ok");
        }
    }

    public class User
    {
        public string Name { get; set; }
        public string Pwd { get; set; }
    }
  • ViewStart

    • 以_ViewStart.cshtml命名,固定名称,不能更换
    • 一般放在视图所在目录的根目录下
    • 自动执行,无需手工调用
    • 不要再ViewStart中做大量的业务操作
  • ViewImport
    • 以_ViewImport.cshtml命名,固定名称,不能更换
    • 只作引入操作
    • 一般放在视图所在目录的根目录下
    • 自动执行,无需手工调用
    • 视图中可以使用@using关键字引入所需命名空间
    • 通过ViewImport做全局性的命名空间引入,减少在每个页面中引入的工作量

第四课 数据验证

  • 数据验证特性ValidationAttribute
  public abstract class ValidationAttribute : Attribute
  {
    /// <summary>Initializes a new instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationAttribute"></see> class.</summary>
    protected ValidationAttribute();

    /// <summary>Initializes a new instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationAttribute"></see> class by using the function that enables access to validation resources.</summary>
    /// <param name="errorMessageAccessor">The function that enables access to validation resources.</param>
    /// <exception cref="T:System.ArgumentNullException"><paramref name="errorMessageAccessor">errorMessageAccessor</paramref> is null.</exception>
    protected ValidationAttribute(Func<string> errorMessageAccessor);

    /// <summary>Initializes a new instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationAttribute"></see> class by using the error message to associate with a validation control.</summary>
    /// <param name="errorMessage">The error message to associate with a validation control.</param>
    protected ValidationAttribute(string errorMessage);

    /// <summary>Gets or sets an error message to associate with a validation control if validation fails.</summary>
    /// <returns>The error message that is associated with the validation control.</returns>
    public string ErrorMessage { get; set; }

    /// <summary>Gets or sets the error message resource name to use in order to look up the <see cref="P:System.ComponentModel.DataAnnotations.ValidationAttribute.ErrorMessageResourceType"></see> property value if validation fails.</summary>
    /// <returns>The error message resource that is associated with a validation control.</returns>
    public string ErrorMessageResourceName { get; set; }

    /// <summary>Gets or sets the resource type to use for error-message lookup if validation fails.</summary>
    /// <returns>The type of error message that is associated with a validation control.</returns>
    public Type ErrorMessageResourceType { get; set; }

    /// <summary>Gets the localized validation error message.</summary>
    /// <returns>The localized validation error message.</returns>
    protected string ErrorMessageString { get; }

    /// <summary>Gets a value that indicates whether the attribute requires validation context.</summary>
    /// <returns>true if the attribute requires validation context; otherwise, false.</returns>
    public virtual bool RequiresValidationContext { get; }

    /// <summary>Applies formatting to an error message, based on the data field where the error occurred.</summary>
    /// <param name="name">The name to include in the formatted message.</param>
    /// <returns>An instance of the formatted error message.</returns>
    public virtual string FormatErrorMessage(string name);

    /// <summary>Checks whether the specified value is valid with respect to the current validation attribute.</summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    /// <returns>An instance of the <see cref="System.ComponentModel.DataAnnotations.ValidationResult"></see> class.</returns>
    public ValidationResult GetValidationResult(
      object value,
      ValidationContext validationContext);

    /// <summary>Determines whether the specified value of the object is valid.</summary>
    /// <param name="value">The value of the object to validate.</param>
    /// <returns>true if the specified value is valid; otherwise, false.</returns>
    public virtual bool IsValid(object value);

    /// <summary>Validates the specified value with respect to the current validation attribute.</summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    /// <returns>An instance of the <see cref="System.ComponentModel.DataAnnotations.ValidationResult"></see> class.</returns>
    protected virtual ValidationResult IsValid(
      object value,
      ValidationContext validationContext);

    /// <summary>Validates the specified object.</summary>
    /// <param name="value">The object to validate.</param>
    /// <param name="validationContext">The <see cref="T:System.ComponentModel.DataAnnotations.ValidationContext"></see> object that describes the context where the validation checks are performed. This parameter cannot be null.</param>
    /// <exception cref="T:System.ComponentModel.DataAnnotations.ValidationException">Validation failed.</exception>
    public void Validate(object value, ValidationContext validationContext);

    /// <summary>Validates the specified object.</summary>
    /// <param name="value">The value of the object to validate.</param>
    /// <param name="name">The name to include in the error message.</param>
    /// <exception cref="T:System.ComponentModel.DataAnnotations.ValidationException"><paramref name="value">value</paramref> is not valid.</exception>
    public void Validate(object value, string name);
  }
  • 常用数据验证

    • RequiredAttribute
    • RegularExpressionAttribute
    • CompareAttribute
    • RangeAttribute
    • MaxAttribute
    • MinAttribute
    • StringLengthAttribute
    • DataTypeAttribute
  • 服务器端使用
    • 使用包含验证规则的类接收数据
    • 使用ModelState.IsValid判断是否符合要求
  • 前端使用
    • 定义强类型视图并传递包含验证规则的业务数据模型
    • 使用HtmlHelper.ValidationFor初始前端验证规则
    • 使用HtmlHelper.ValidationMessageFor生成提示文字
    public class UserLogin
    {
        [Required(ErrorMessage = "用户名不能为空")]
        [StringLength(10,ErrorMessage = "用户名长度不能超过10位")]
        public string UserName { get; set; }

        //[Required(ErrorMessage = "密码不能为空")]
        [StringLength(6,ErrorMessage = "密码长度不能超过6位")]
        public string Password { get; set; }
    }
    public class FormController : Controller
    {
        public IActionResult Index()
        {
            return View(new UserLogin());
        }

        public IActionResult PostData(UserLogin login)
        {
            return Content(ModelState.IsValid?"数据有效":"数据无效");
        }
    }
@model Lesson2.Models.UserLogin
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
</head>
<body>
    <form asp-action="PostData" method="post">
        <table>
            <tr>
                <td>用户名</td>
                <td>@Html.TextBoxFor(m => m.UserName)</td>
                <td>@Html.ValidationMessageFor(m => m.UserName)</td>
            </tr>
            <tr>
                <td>密码</td>
                <td>@Html.PasswordFor(m => m.Password)</td>
                <td>@Html.ValidationMessageFor(m => m.Password)</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="登录" /></td>
                <td></td>
            </tr>
        </table>
    </form>
</body>
</html>

第五课 路由规则

  • 路由

    • 定义用户请求与控制器方法之前的映射关系
  • 路由配置
    • IRouteBuilder

      • 通过MapRoute方法配置路由模板
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "admin_default",
            template: "admin/{controller=Home}/{action=Index}/{id?}");
    });
  • RouteAttribute

    • 应用在控制器及方法上
    • 通过Template属性配置路由模板
    [Route("admin/form")]
    public class FormController : Controller
    {
        [Route("index")]
        public IActionResult Index()
        {
            return View(new UserLogin());
        }

        public IActionResult PostData(UserLogin login)
        {
            return Content(ModelState.IsValid?"数据有效":"数据无效");
        }
    }
  • 路由约束

    • 对路由数据进行约束
    • 只有约束满足条件才能匹配成功
约束 示例 说明
required "Product/{ProductName:required}" 参数必选
alpha "Product/{ProductName:alpha}" 匹配字母,大小写不限
int "Product/{ProductId:int}" 匹配int类型
··· ··· ···
composite "Product/{ProductId:composite}" 匹配composite类型
length "Product/{ProductName:length(5)}" 长度必须是5个字符
length "Product/{ProductName:length(5)}" 长度在5-10之间
maxlength "Product/{ProductId:maxlength(10)}" 最大长度为10
minlength "Product/{ProductId:minlength(3)}" 最小长度为3
min "Product/{ProductId:min(3)}" 大于等于3
max "Product/{ProductId:max(10)}" 小于等于10
range "Product/{ProductId:range(5,10)}" 对应的数组在5-10之间
regex "Product/{ProductId:regex(^\d{4}$)}" 符合指定的正则表达式
  • 路由数据

    • 路由数据也是请求数据的一部分
    • 路由数据与表单数据一样,也可以绑定到参数上
    • 默认是通过名称进行匹配,也可以通过FormRouteAttribute匹配参数与路由数据的映射关系
    public IActionResult Index([FromRoute] int? id)
    {
        return View();
    }

第六课 应用发布与部署

  • 发布

    • 发布方法

      • 使用Visual Studio发布应用:项目右键 -> 发布 -> 发布方式选择...
      • 使用dotnet publish命令行工具发布:dotnet publish --configuration Release --runtime win7-x64 --output c:\svc
  • 视图预编译
    • 少了运行时编译过程,启动速度快
    • 预编译后,整个程序包更小
    • 可以通过MvcRazorCompileOnPublish配置是否开启,默认是开启状态
      • 关闭视图预编译:

        • 打开项目的.csproj文件
        • 配置MvcRazorCompileOnPublish为false
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <!-- 关闭视图预编译 -->
    <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.1" />
  </ItemGroup>

</Project>
<!-- 依赖框架的部署 (FDD) -->
<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  <SelfContained>false</SelfContained>
  <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
<!-- 独立部署 (SCD) -->
<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
    ...
    ...
    ...

源码地址

到此这篇关于ASP.NET CORE基础教程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • ASP.NET Core的中间件与管道介绍

    今天来讨论一个ASP.NET Core 很重要概念管道和中间件,在ASP.NET Core中,针对HTTP请求采用pipeline也就是通常说的管道方式来处理,而管道容器内可以挂载很多中间件(处理逻辑)“串联”来处理HTTP请求,每一个中间件都有权决定是否需要执行下一个中间件,或者直接做出响应.这样的机制使得HTTP请求能够很好的被层层处理和控制,并且层次清晰处理起来甚是方便. 示意图如下: 为了再次说明管道和中间件的概念,举一个官方给出的权限验证的例子,中间件A,B分别按顺序挂载在管道容器中,

  • ASP.NET Core托管模型CreateDefaultBuilder()方法

    让我们讨论一下 CreateDefaultBuilder() 方法究竟对配置和设置 Web 服务器的作用.从托管的角度来看,一个ASP.NET Web 应用程序可以通过两种方式托管,即进程托管(InProcess)或进程外托管(OutOfProcess). 注:当我们使用任何模板创建新 ASP.NET Core Web 应用程序时,默认情况下,使用InProcess 托管创建项目文件,该托管用于在 IIS 或 IIS Express 方案中托管应用程序. 如何验证是否在进程内? 为了验证上面的观

  • ASP.NET Core开发环境安装配置

    ASP.NET Core环境设置 1.如何设置用于.NetCore应用程序开发的开发机器 2.安装SDK和IDE 3.验证安装 开发和.NET Core应用程序所需的工具和软件 1.设备:(Windows.Mac.Linux) 2.IDE:Visual Studio.Visual Code 3.NetSDK:软件开发工具包,此工具包有助于开发和运行系统中的应用程序. 如何为构建 .NET Core/ASP.NET Core应用程序准备开发环境? NET Core可以通过两种方式安装: 1.通过安

  • ASP.NET Core 3.0轻量级角色API控制授权库

    说明 ASP.NET Core 3.0 一个 jwt 的轻量角色/用户.单个API控制的授权认证库 最近得空,重新做一个角色授权库,而之前做了一个角色授权库,是利用微软的默认接口做的,查阅了很多文档,因为理解不够,所以最终做出了有问题. 之前的旧版本 https://github.com/whuanle/CZGL.Auth/tree/1.0.0 如果要使用微软的默认接口,我个人认为过于繁杂,而且对于这部分的资料较少... 使用默认接口实现授权认证,可以参考我另一篇文章 ASP.NET Core

  • ASP.NET Core环境变量和启动设置的配置教程

    在这一部分内容中,我们来讨论ASP.NET Core中的一个新功能:环境变量和启动设置,它将开发过程中的调试和测试变的更加简单.我们只需要简单的修改配置文件,就可以实现开发.预演.生产环境的切换. ASPNETCORE_ENVIRONMENT ASP.NET Core控制环境切换最核心的东西是"ASPNETCORE_ENVIRONMENT"环境变量,它直接控制当前应用程序运行的环境类型.您可以通过在项目上右键菜单选择"属性"选项,然后切换到"调试"

  • 理解ASP.NET Core 启动类(Startup)

    目录 准备工作:一份ASP.NET Core Web API应用程序 Startup类 Startup构造函数 ConfigureServices Configure 省略Startup类 IStartupFilter IHostingStartup HostingStartup 程序集 HostingStartup 特性 激活HostingStarup程序集 1.使用环境变量(推荐) 2.在程序中配置 多环境配置 环境配置方式 基于环境的 Startup 1.将IWebHostEnvironm

  • ASP.NET Core中HttpContext详解与使用

    “传导体” HttpContext 要理解 HttpContext 是干嘛的,首先,看图 图一 内网访问程序 图二 反向代理访问程序 ASP.NET Core 程序中,Kestrel 是一个基于 libuv 的跨平台ASP.NET Core web服务器.不清楚 Kerstrel 没关系,以后慢慢了解. 我们可以理解成,外部访问我们的程序,通过 Http 或者 Https 访问,例如https://localhost:44337/Home/Index,需要通过一个网址,来寻向访问特定的页面. 访

  • ASP.NET Core基础之启动设置

    这一章,我们了解一下launchSettings.json的作用. 打开launchSettings.json 文件后,默认情况下,您将找到以下代码. { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http:

  • ASP.NET Core基础之Main方法讲解

    为什么ASP.NET Core采用Main方法? 需要记住的最重要的一点是,ASP.NET Core Web 应用程序最初作为控制台应用程序启动,Main() 方法是应用程序的入口点.因此,当我们执行ASP.NET Core Web应用程序时,首先它寻找 Main() 方法,这是执行开始的方法.然后,Main()方法将ASP.NET配置并启动它.此时,应用程序将成为ASP.NET Core Web应用程序. 如果进一步查看 Main() 方法的正文,则会发现它通过将命令行参数 args 作为参数

  • ASP.NET CORE基础教程

    目录 第一课 基本概念 第二课 控制器的介绍 第三课 视图与表单 第四课 数据验证 第五课 路由规则 第六课 应用发布与部署 源码地址 第一课 基本概念 基本概念 Asp.Net Core Mvc是.NET Core平台下的一种Web应用开发框架 符合Web应用特点 .NET Core跨平台解决方案 MVC设计模式的一种实现 环境准备 安装最新版Visual Studio 2017 安装最新版.NET Core Sdk 第二课 控制器的介绍 控制器定义方式: 命名以Controller结尾 使用

  • ASP.NET Core基础之Startup类

    ASP.NET Core必须包含Startup类.它就像 Global.asax 文件,我们传统的 .NET 应用程序.如名称建议的那样,在应用程序启动时首先执行它.在程序类的Main方法中配置主机时,可以使用UseStartup()扩展方法配置启动类.请查看下面的程序类,并重点介绍 WebBuilder.UseStartup() 方法. 名称"Startup"是按照ASP.NET Core约定进行的. 但是,您可以给Startup类指定任何名称,只需在UseStartup ()方法中

  • ASP.NET Core基础之异常中间件

    了解异常中间件 首先,使用ASP.NET模板创建一个核心应用程序.默认情况下,ASP.NET核心应用程序只是返回应用程序未处理的异常的状态代码.如下所示,我们引发异常. 运行应用程序时,将得到以下输出. 如上图所示,它为您提供的状态代码为 500,这意味着内部服务器错误.但是,作为开发人员,在开发应用程序时,您应该知道有关页面上异常的详细信息,以便可以采取必要的操作来修复错误. 如何使用异常中间件? 如果希望应用程序显示显示有关未处理异常的详细信息的页面,则需要在请求处理管道中配置开发人员异常页

  • ASP.NET Core基础之请求处理管道

    了解ASP.NET处理管道 为了理解ASP.NET Core中的请求处理管道概念,让我们修改Startup类的Configure()方法,如下所示. 在这里,我们将三个中间件组件注册到请求处理管道中. 如您所见,前两个组件是使用Use() 扩展方法注册的,因此它们有机会在请求处理管道中调用下一个中间件组件. 最后一个使用Run() 扩展方法注册,因为它将成为我们的终止组件,即它将不会调用下一个组件. 了解ASP.NET Core请求处理管道执行顺序 为了理解这一点,让我们将上面的输出与下图进行比

  • ASP.NET Core基础之中间件

    什么是ASP.NET Core Middleware? ASP.NET Core中间件组件是被组装到应用程序管道中以处理HTTP请求和响应的软件组件(从技术上来说,组件只是C#类). ASP.NET Core应用程序中的每个中间件组件都执行以下任务. 选择是否将 HTTP 请求传递给管道中的下一个组件.这可以通过在中间件中调用下一个 next() 方法实现. 可以在管道中的下一个组件之前和之后执行工作. 在ASP.NET Core中,已经有很多内置的中间件组件可供使用,您可以直接使用它们. 如果

  • ASP.NET Core配置教程之读取配置信息

    提到"配置"二字,我想绝大部分.NET开发人员脑海中会立马浮现出两个特殊文件的身影,那就是我们再熟悉不过的app.config和web.config,多年以来我们已经习惯了将结构化的配置信息定义在这两个文件之中.到了.NET Core的时候,很多我们习以为常的东西都发生了改变,其中也包括定义配置的方式.总的来说,新的配置系统显得更加轻量级,并且具有更好的扩展性,其最大的特点就是支持多样化的数据源.我们可以采用内存的变量作为配置的数据源,也可以直接配置定义在持久化的文件甚至数据库中. 由

  • ASP.NET CORE学习教程之自定义异常处理详解

    为什么异常处理选择中间件? 传统的ASP.NET可以采用异常过滤器的方式处理异常,在ASP.NET CORE中,是以多个中间件连接而成的管道形式处理请求的,不过常用的五大过滤器得以保留,同样可以采用异常过滤器处理异常,但是异常过滤器不能处理MVC中间件以外的异常,为了全局统一考虑,采用中间件处理异常更为合适 为什么选择自定义异常中间件? 先来看看ASP.NET CORE 内置的三个异常处理中间件 DeveloperExceptionPageMiddleware, ExceptionHandler

  • ASP.NET Core利用UrlFirewall对请求进行过滤的方法示例

    一. 前言 UrlFirewall 是一个开源.轻便的对http请求进行过滤的中间件,可使用在webapi或者网关(比如Ocelot),由我本人编写,并且开源在github:https://github.com/stulzq/UrlFirewall  (本地下载) 二.UrlFirewall 介绍 UrlFirewall 是一款http请求过滤中间件,可以和网关(Ocelot)搭配,实现屏蔽外网访问内部接口,只让内部接口之间相互通讯,而不暴露到外部.它支持黑名单模式和白名单模式,支持自定义htt

随机推荐