在.NET Core中,可以通过创建一个自定义的中间件或者在Startup.cs
文件中配置服务来实现跨控制器的变量共享。以下是两种常见的方法:
public static class SharedContext
{
public static string MyVariable { get; set; }
}
Startup.cs
中注册这个服务:public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SharedContext>();
services.AddControllers();
}
public class SetSharedVariableMiddleware
{
private readonly RequestDelegate _next;
public SetSharedVariableMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 假设我们从某个地方获取变量值
string value = "SomeValue";
SharedContext.MyVariable = value;
await _next(context);
}
}
Startup.cs
中使用这个中间件:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseMiddleware<SetSharedVariableMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public class MyController : ControllerBase
{
public IActionResult Index()
{
string variable = SharedContext.MyVariable;
return Ok(variable);
}
}
public class MyHttpContextFeature : IHttpContextFeature
{
private readonly HttpContext _httpContext;
public MyHttpContextFeature(HttpContext httpContext)
{
_httpContext = httpContext;
}
public HttpContext HttpContext => _httpContext;
}
Startup.cs
中注册这个特征:public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddControllers(options =>
{
options.Filters.Add(new MyHttpContextFeatureAttribute());
});
}
public abstract class BaseController : ControllerBase
{
protected string MyVariable => HttpContext.Features.Get<MyHttpContextFeature>()?.HttpContext.Items["MyVariable"] as string;
}
public class MyController : BaseController
{
public IActionResult Index()
{
string variable = MyVariable;
return Ok(variable);
}
}
public class SetSharedVariableMiddleware
{
private readonly RequestDelegate _next;
public SetSharedVariableMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 设置变量
context.Items["MyVariable"] = "SomeValue";
await _next(context);
}
}
这两种方法都可以实现在所有控制器中共享变量的目的。选择哪种方法取决于你的具体需求和偏好。依赖注入更适合于需要在多个服务之间共享状态的场景,而HttpContext特征则更适合于与HTTP请求紧密相关的上下文信息。
领取专属 10元无门槛券
手把手带您无忧上云