概述
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;
}
}
}
3、CustomExceptionMiddleware.cs
HttpContext.Response.StatusCode = 403 拦截
using Newtonsoft.Json;
namespace QualityControl.WebAPI.Filters
{
/// <summary>
///
/// </summary>
public class CustomExceptionMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public CustomExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
///
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex.Message);
}
finally
{
var statusCode = httpContext.Response.StatusCode;
var msg = "";
switch (statusCode)
{
case 401:
msg = "未授权";
break;
case 403:
msg = "拒绝访问";
break;
case 404:
msg = "未找到服务";
break;
case 405:
msg = "405 Method Not Allowed";
break;
case 502:
msg = "请求错误";
break;
}
if (!string.IsNullOrWhiteSpace(msg))
{
await HandleExceptionAsync(httpContext, msg);
}
}
}
private async Task HandleExceptionAsync(HttpContext httpContext, string msg)
{
httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
httpContext.Response.ContentType = "application/json;charset=utf-8";
var message = JsonConvert.SerializeObject(new { code = 0, message = "未经授权的非法请求" });
await httpContext.Response.WriteAsync(message).ConfigureAwait(false);
}
}
}
*
*
*
*
*
最后
以上就是整齐荔枝为你收集整理的ASP.NET Core Middleware 中间件 使用期限,403拦截的全部内容,希望文章能够帮你解决ASP.NET Core Middleware 中间件 使用期限,403拦截所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复