通过自定义middlewear c#Asp.net 5.0访问类libaray中的HttpContext



如果我们想访问类库中的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>();
}
}
}

我的类库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吗?你会把这个类注入startup.cs吗?

如果您要注入,那么您可以在asp.net应用程序中使用其他服务。像httpcontextocessor或else来满足您的需求。如果你不注入它,也不想将httpcontext传递给它,你就无法获得它

关于如何使用它的详细信息,如下所示:

注入:

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

MyDependency类:

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}");
}
}

最新更新