ASP.NET Core 中间件 ASP.NET Core 的客户端 IP 安全列表
中间件是一种装配到应用管道以处理请求和响应的软件。 每个组件:
- 选择是否将请求传递到管道中的下一个组件。
- 可在管道中的下一个组件前后执行工作。
请求委托用于生成请求管道。 请求委托处理每个 HTTP 请求。
1、Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Web
{
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.AddControllers();
services.AddDbContext<SqlDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
#region 中间件
app.UseMiddleware<AdminSafeListMiddleware>(Configuration["AdminSafeList"]);
app.UseMiddleware<DueDateMiddleware>();
#endregion
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
2、DueDateMiddleware.cs
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
namespace WebApi
{
public class DueDateMiddleware
{
private readonly RequestDelegate _next;
public DueDateMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
DateTime dueDate = new DateTime(2024, 3, 25);
DateTime currentDate = GetDate("http://www.baidu.com", dueDate);
if (dueDate < currentDate)
{
context.Response.ContentType = "application/json;charset=utf-8";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
code = 401,
message = "使用期限已到,请联系管理员"
}));
}
else
{
await _next(context);
}
}
public DateTime GetDate(string url, DateTime dueDate)
{
DateTime dt = dueDate.AddDays(10);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
var lastModified = response.LastModified;
dt = Convert.ToDateTime(lastModified);
}
catch (WebException e)
{
response = (HttpWebResponse)e.Response;
}
finally
{
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return dt;
}
}
}
* * *
|