【NetCore】09-中间件

中间件:掌控请求处理过程的关键

1. 中间件

1.1 中间件工作原理

中间件工作原理

1.2 中间件核心对象

  • IApplicationBuilder
  • RequestDelegate

IApplicationBuilder可以通过委托方式注册中间件,委托的入参也是委托,这就可以将这些委托注册成一个链,如上图所示;最终会调用Builder方法返回一个委托,这个委托就是把所有的中间件串起来后合并成的一个委托方法,Builder的委托入参是HttpContext(实际上所有的委托都是对HttpContext进行处理);
RequestDelegate是处理整个请求的委托。

中间件的执行顺序和注册顺序是相关的

//注册委托方式,注册自己逻辑
 // 对所有请求路径
            app.Use(async (context, next) =>
            {
                await next();
                await context.Response.WriteAsync("Hello2");
            });

            // 对特定路径指定中间件,对/abc路径进行中间件注册处理
            app.Map("/abc", abcBuilder =>
            {
            	// Use表示注册一个完整的中间件,将next也注册进去
                abcBuilder.Use(async (context, next) =>
                {
                    await next();
                    await context.Response.WriteAsync("abcHello");
                });
            });

            // Map复杂判断,判断当前请求是否符合某种条件
            app.MapWhen(context =>
            {
                return context.Request.Query.Keys.Contains("abc");
            }
            , builder =>
            {
                // 使用Run表示这里就是中间件的执行末端,不再执行后续中间件
                builder.Run(async context =>
                {
                    await context.Response.WriteAsync("new abc");
                });
            });

应用程序一旦开始向Response进行write时,后续的中间件就不能再操作Head,否则会报错
可以通过context.Resopnse.HasStarted方法判断head是否已经被操作

  • 设计自己的中间件
    中间件的设计时才有的约定的方式,即在方法中包含Invoke或者InvokeAsync,如下:
public class MyMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<MyMiddleware> logger;

        public MyMiddleware(RequestDelegate next,ILogger<MyMiddleware> logger)
        {
            this.next = next;
            this.logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            using (logger.BeginScope("TraceIndentifier:{TraceIdentifier}",context.TraceIdentifier))
            {
                logger.LogDebug("Start");
                await next(context);
                logger.LogDebug("End");
            }
        }
    }

public static class MyBuilderExtensions
{
	public  static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder app)
	{
		return app.UseMiddleware<MyMiddleware>();
	}
}

// 中间件使用
app.UseMyMiddleware();

2.异常处理中间件:区分真异常和逻辑异常

2.1 处理异常的方式

  • 异常处理页
  • 异常处理匿名委托方法
  • IExceptionFilter
  • ExceptionFilterAttribute
// startup中的Configure
 if (env.IsDevelopment())
 {
      app.UseDeveloperExceptionPage();// 开发环境下的异常页面,生产环境下是需要被关闭,页面如下图所示
      app.UseSwagger();
      app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "LoggingSerilog v1"));
}

在这里插入图片描述

2.1.1 日常错误处理–定义错误页的方法
// startup中的Configure
app.UseExceptionHandler("/error");

// 控制器
public class ErrprController : Controller
{
	[Route("/error")]
	public IActionResult Index()
	{
		// 获取上下文中的异常
		var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
		var ex = exceptionHandlerPathFeature?.Error;
		
		var knowException = ex as IKnowException;
		
		if(knowException == null)
		{
			var logger = HttpContext.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(ex,ex.Message);
			knowException = KnowException.Unknow;
		}
		else
		{
			knowException = KnowException.FromKnowException(knowException);
		}
		return View(knowException);
	}
}

// 定义接口
public interface IKnowException
{
	public string Message {get;}
	
	public int ErrorCode {get;}

	public object[] ErrorData {get;}
}

// 定义实现
public class KnowException : IKnowException
{
	public string Message {get;private set;}

	public int ErrorCode {get;private set;}

	public object[] ErrorData {get;private set;}

	public readonly static IKnowException Uknow = new KnowException{Message = "未知错误",ErrorCode = 9999};

	public static IKnowException FromKnowException(IKnowException exception)
	{
		return new KnowException{Message = exception.Message,ErrorCode = exception.ErrorCode,ErrorData = exception.ErrorData};
	}
}

// 需要定义一个错误页面 index.html,输出错误Message和ErrorCode
2.1.2 使用代理方法处理异常
// startup中的Configure
app.UseExceptionHandler(errApp =>
{
	errApp.Run(async context =>
	{
		var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
		var ex = exceptionHandlerPathFeature?.Error;
		var knowException = ex as IKnowException;
		
		if(knowException == null)
		{
			var logger = HttpContext.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(exceptionHandlerPathFeature.Error,exceptionHandlerPathFeature.Error.Message);
			knowException = KnowException.Unknow;
			context.Response.StatusCode = StatusCodes.Status500InternalServerError;
		}
		else
		{
			knowException = KnowException.FromKnowException(knowException);
			context.Response.StatusCode = StatusCodes.Status200OK;
		}
		var jsonOptions = context.RequestServices.GetService<Options<JsonOptions>>();
		context.Response.ContextType = "application/json";charset=utf-8";
		await context.Response.WriteAsync(System.Text.Json.JsonSerializer(knowException,jsonOptions.Value));
	});
});

  • 未知异常输出Http500响应,已知异常输出Http200
    因为监控系统会对Http响应码进行识别,如果返回的500比率比较高的时候,会认为系统的可用性有问题,告警系统会发出警告。对已知异常进行200响应能够让告警系统正常运行,能够正确识别系统一些未知的错误,使告警系统更加灵敏,避免了业务逻辑的异常干扰告警系统
2.1.3 异常过滤器 IExceptionFilter

异常过滤器是作用在整个MVC框架体系之下,在MVC整个声明周期中发生作用,也就是说它只能工作早MVC Web Api的请求周期里面

// 自定义异常过滤器
public class MyException : IExceptionFilter
{
	public void OnException(ExceptionContext context)
	{
		IKnowException knowException = context.Exception as IKnowException;
		if(knowException == null)
		{
			var loger = context.HttpContext.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(context.Exception,context.Exception.Message);
			knowException = KnowException.UnKnow;
			context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
		}
		else
		{
			knowException = KnowException.FromKnowException(knowException);
			context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
		}
		context.Result = new JsonResult(knowException)
		{
			ContextType = "application/json:charset=utf-8"
		}
	}
}

// startup注册
public void ConfigureServices(IServiceCollection services)
{
	services.AddMvc(mvcoption => 
	{
		mvcOptions.Filters.Add<MyExceptionFilter>();
	}).AddJsonOptions(jsonOptions => {
		jsonOptions.JsonSerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscapt
	});
}



2.1.4 特性过滤 ExceptionFilterAttribute
public class MyExceptionFilterAttriburte  : ExceptionFilterAttribute
{
	public override void OnException(ExceptionContext context)
	{
		IKnowException knowException = context.Exception as IKnowException;
		if(knowException == null)
		{
			var logger = context.HttpContext.RequestServices.GetServices<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(context.Exception,context.Exception.Message);
			knowException = KnowException.UnKnow;
			context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
		}
		else
		{
			knowException = KnowException.FromKnowException(knowException);
			context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
		}
		context.Result = new JsonResult(knowException)
		{
			ContextType = "application/json:charset=utf-8"
		}
	}
}

// 使用方式
在Controller控制器上方标注[MyExceptionFilter]
或者在 startup中ConfigureServices注册
services.AddMvc(mvcoption => 
	{
		mvcOptions.Filters.Add<MyExceptionFilterAttribute>();
	});
2.1.5 异常处理技巧总结
  • 用特定的异常类或接口表示业务逻辑异常
  • 为业务逻辑异常定义全局错误码
  • 为未知异常定义定义特定的输出信息和错误码
  • 对于已知业务逻辑异常响应HTTP 200(监控系统友好)
  • 对于未预见的异常响应HTTP 500
  • 为所有的异常记录详细的日志

3 静态文件中间件: 前后端分离开发合并部署

3.1 静态文件中间件的能力

  • 支持指定相对路径
  • 支持目录浏览
  • 支持设置默认文档
  • 支持多目录映射
// startup的Configure方法中
app.UseDefaultFiles();// 设置默认访问根目录文件index.html
app.UseStaticFiles();// 将www.root目录映射出去

如果需要浏览文件目录,需要如下配置

// startup中的ConfigureServices中配置
services.AddDirectoryBrowser();

// startup的Configure方法中
app.UseDirectoryBrowser();
app.UseStaticFiles();

3.2 注册使用非www.root目录

// startup的Configure方法中
app.UseStaticFiles();

app.UseStaticFiles(new StaticFileOptions
{
	// 将程序中名为file文件目录注入
	RequestPath = "/files",// 设置文件指定访问路径,将文件目录映射为指定的Url地址
	FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"file"))
});


实际生产中会遇到将非api请求重定向到指定目录,采用如下配置

// startup的Configure方法中
app.MapWhen(context => 
{
	return !context.Request.Path.Value.StartWith("/api");
},appBuilder => 
{
	var option = new RewriteOptions();
	option.AddRewrite(".*","/index.html",true);
	appBuilder.UseRewriter(option);
	appBuilder.UseStaticFiles();
});

4 文件提供程序:将文件放在任何地方

4.1 文件提供程序核心类型

  • IFileProvider
  • IFileInfo
  • IDirectoryContexts

4.2 内置文件提供程序

  • PhysicalFileProvider⇒ 物理文件提供程序
  • EmbeddedFileProvider ⇒ 嵌入式文件提供程序
  • CompositeFileProvoder ⇒ 组合文件提供程序,将各种文件程序组合成一个目录
// 映射指定目录文件- 物理文件
IFileProvider provider1 = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
// 获取文件目录下内容
var contents = provider1.GetDirectoryContents("/");
// 输出文件信息
foreach (var item in contents)
{
    var stream = item.CreateReadStream();// 获取文件流
    Console.WriteLine(item.Name);
}

// 嵌入式文件
IFileProvider fileProvider2 = new EmbeddedFileProvider(typeof(Program).Assembly);
var html = fileProvider2.GetFileInfo("file.html");// file.html文件属性设置为嵌入的资源

// 组合文件提供程序
IFileProvider fileProvider3 = new CompositeFileProvider(provider1,fileProvider2);
var contexts3 = fileProvider3.GetDirectoryContents("/");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: .NET Core 是由微软开发的跨平台版本的 .NET 框架。WS-Federation 是用于实现单点登录 (SSO) 的一种 Web 服务协议。 在 .NET Core 中实现 WS-Federation 的示例可能需要使用第三方库,如 Microsoft.AspNetCore.Authentication.WsFederation。 示例代码可能长这样: ``` using Microsoft.AspNetCore.Authentication.WsFederation; ... services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = WsFederationDefaults.AuthenticationScheme; }) .AddWsFederation(options => { options.MetadataAddress = "https://your-sts.com/federationmetadata/2007-06/federationmetadata.xml"; options.Wtrealm = "https://your-app.com/"; }); ``` 这个是一个概要,具体实现需要更多代码和配置以及参考文档进行查询 ### 回答2: Ws-Federation 是一种基于Web服务的信任协议,用于实现单点登录(SSO)和身份提供者和服务提供者之间的身份管理。.Net Core是微软推出的跨平台开发框架,与传统的.Net框架相比,它更加轻量级、灵活且易于扩展。 在.Net Core中实现Ws-Federation可以通过使用IdentityServer来实现。IdentityServer是一个开源的身份和访问控制服务器,它支持多种身份验证方式和协议,包括Ws-Federation。 下面以一个简单的示例来说明如何在.Net Core中使用Ws-Federation: 首先,我们需要创建一个IdentityServer的实例。可以使用IdentityServer4这个开源项目,它已经集成了Ws-Federation的支持。我们可以在项目中引入IdentityServer4包,并配置IdentityServer的选项。 然后,我们需要配置IdentityServer的客户端和身份提供者。可以在代码中配置或者使用存储来管理。 接下来,我们需要在.Net Core应用程序中添加对Ws-Federation的支持。可以使用AspNet.Security.WsFederation这个包来实现。 在应用程序中,我们需要添加一个Ws-Federation中间件,并配置它的选项,包括身份提供者的元数据地址、Realm等。 然后,我们可以在应用程序中编写需要进行身份验证的控制器和视图。 最后,我们需要启动IdentityServer和应用程序,以便能够通过浏览器访问应用程序。当用户访问应用程序时,会被重定向到身份提供者进行身份验证,验证通过后会返回一个令牌,应用程序可以使用该令牌来验证用户的身份。 总之,通过使用.Net Core和IdentityServer,我们可以很方便地实现Ws-Federation协议,实现跨平台的单点登录和身份管理。使用IdentityServer4和AspNet.Security.WsFederation这两个开源项目,我们可以更加简化和高效地开发和配置。 ### 回答3: WS-Federation 是一种用于建立信任关系的开放式标准协议,.NET Core 是微软开发的跨平台开发框架。下面以一个例子来说明如何在.NET Core 中使用 WS-Federation。 假设我们有一个公司内部的网站,需要与另外一个外部系统进行集成。外部系统使用了 WS-Federation 协议进行身份验证和授权。 首先,我们需要在我们的.NET Core 应用程序中引入相关的包,例如 Microsoft.AspNetCore.Authentication.WsFederation。 然后,我们需要配置身份验证服务,指定外部系统的元数据地址和令牌颁发方的地址。我们可以使用 AddWsFederation() 方法来配置。 接下来,我们需要编写登录和注销的控制器方法。对于登录方法,我们可以使用 Challenge() 方法来发起身份验证请求,并将外部系统的地址作为参数传递。对于注销方法,我们可以使用 SignOut() 方法来退出登录。 在网站的某个页面,我们可以添加一个按钮或者链接,当用户点击时,调用登录控制器方法,将用户重定向到外部系统的登录页面。用户在外部系统进行登录后,将被重定向回我们的网站,并返回一个包含用户信息的安全令牌。 我们可以在受保护的页面或者控制器方法中添加 [Authorize] 属性来限制只有经过身份验证的用户才能访问。当用户访问这些受保护的资源时,系统会自动使用 WS-Federation 协议来验证用户的身份,并根据授权策略决定是否允许访问。 当用户想要注销时,我们可以在页面或者控制器方法中添加一个按钮或者链接,调用注销控制器方法,将用户从当前会话中退出,并重定向至外部系统的注销页面。 通过上述步骤,我们就成功地在.NET Core 应用程序中集成了 WS-Federation 协议,实现了与外部系统的身份验证和授权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值