Hi,@melon NG
I tried with your codes and it got an error ,have you missed any codes?
I Noticed your inject Gloable into your middleware,but you didn't implement the intereface, You could check this document first,
I tried with two solutions and they both worked,
Solution1:
public static class GlobalStatic
{
public static IServiceProvider ServiceProvider { get; set; }
public static string GetUA()
{
var accessor = (IHttpContextAccessor)ServiceProvider.GetService(typeof(IHttpContextAccessor));
var UA=accessor.HttpContext?.Request.Headers["User-Agent"].ToString();
return UA;
}
}
in startup:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
......
GlobalStatic.ServiceProvider = app.ApplicationServices;
.......
}
Solution2:
public interface IGlobal
{
string GetUA();
}
public class Global: IGlobal
{
private readonly IHttpContextAccessor _accessor;
public Global(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public string GetUA()
{
return _accessor.HttpContext?.Request.Headers["User-Agent"].ToString();
}
}
in Startup:
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddHttpContextAccessor();
services.AddSingleton<IGlobal,Global>();
services.AddControllersWithViews();
......
}
MiddleWare:
public class CustomMiddleware
{
readonly RequestDelegate _next;
readonly IGlobal _G;
Random R = new Random(DateTime.Now.Millisecond);
public CustomMiddleware(
RequestDelegate next,IGlobal G)
{
_next = next;
_G = G;
}
public async Task Invoke(HttpContext context)
{
string test1 = GlobalStatic.GetUA();
string test2 = _G.GetUA();
await _next(context);
}
}
Result:
----------
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards
RuikaiFeng