通过自定义中间件 c# Asp.net 5.0 访问 class 库中的 HttpContext

Getting access to HttpContext in class libaray through custom middlewear c# Asp.net 5.0

如果我们想访问 class 库中的 HttpContext,我们可以像这样简单地传递它:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAppLib;

namespace WebApplication
{
    public class WebAppMiddleware
    {
        private readonly RequestDelegate _next;

        public WebAppMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            Test test = new test();
            test.TestMethod(httpContext) <--- passing the current httpcontext to the method.

            // Return httpcontext
            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class WebAppMiddlewareExtensions
    {
        public static IApplicationBuilder UseWebAppMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<WebAppMiddleware>();
        }
    }
}

我的 Class 库 dll 文件(在 csproj 文件中包含 FrameworkReference Include="Microsoft.AspNetCore.App")

using Microsoft.AspNetCore.Http;

namespace WebAppLib
{
    public class Test
    {
        public void TestMethod(HttpContext httpContext)
        {
            httpContext.Response.WriteAsync("hello from haldner");
            // continue with context instance
        }
    }
}

我想知道是否还有其他方法可以做到这一点?基本上我想避免将“httpContext”传递给我的方法,我在我的自定义中间件中 运行。

你能告诉我你想如何使用这个 WebAppLib 吗?你会把这个 class 注入 startup.cs 吗?

如果您要注入,那么您可以在 asp.net 应用程序中使用其他服务。喜欢 httpcontextaccessor 或其他实现您的要求。如果你不注入,又不想把httpcontext传进去,你是拿不到的。

详细使用方法,如下:

注入:

 services.AddScoped<IMyDependency, MyDependency>();
 services.AddHttpContextAccessor();

MyDependency class:

public class MyDependency : IMyDependency
{

    private IHttpContextAccessor _context;
    public MyDependency(IHttpContextAccessor context) {
        _context = context;

    }


    public void WriteMessage(string message)
    {
        var path=  _context.HttpContext.Request.Path;

        Console.WriteLine($"MyDependency.WriteMessage Message: {message}");
    }
}