C# dotnet core 2 将数据从中间件/过滤器传递到 Controller 方法

标签 c# .net-core asp.net-core-2.0

目前我们正在使用 dotnet core 2 编写一个网络应用程序。

我们实际上创建了某种多主机平台,我们可以在其中根据传递给我们应用程序的 url 注册新客户端。

但是目前我们想创建一个中间件/过滤器来验证我们客户的。

实际上我们想做的是从数据库中拉取一个对象并检查它是否存在,如果存在,我们要调用 Controller 方法并使该对象可访问,如果不存在,我们实际上要中止并显示错误页面。

我们已经完成的工作是创建一个过滤器/中间件来执行此操作,但是我们无法找到一种方法来访问我们已经在 Controller 方法中的过滤器/中间件中提取的对象。

真的有任何文档可以做到这一点吗?

我实际上试图从以下方面找出答案: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters

但他们没有描述一种方法,只是在操作之前/之后实际做一些事情。

最佳答案

您可以使用 HttpContext.Items 将对象添加到上下文中文档说明:

The Items collection is a good location to store data that is needed only while processing one particular request. The collection's contents are discarded after each request. The Items collection is best used as a way for components or middleware to communicate when they operate at different points in time during a request and have no direct way to pass parameters.

例如,在你的中间件中:

public class MySuperAmazingMiddleware
{
    private readonly RequestDelegate _next;

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

    public Task Invoke(HttpContext context)
    {
        var mySuperAmazingObject = GetSuperAmazingObject();

        context.Items.Add("SuperAmazingObject", mySuperAmazingObject );

        // Call the next delegate/middleware in the pipeline
        return this._next(context);
    }
}

然后稍后在您的操作方法中,您可以读取该值:

var mySuperAmazingObject = (SuperAmazingObject)HttpContext.Items["mySuperAmazingObject"];

关于C# dotnet core 2 将数据从中间件/过滤器传递到 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601757/

相关文章:

c# - TemplateBinding 不适用于文本框文本

c# - 网络核心 : Find Primary Key of Entity Framework Core and Reflection

azure - Netcoreapp2.0 无法在 Azure 应用服务中启动,出现错误 500 并且没有日志

angular - TypeError : webpack. CopyWebpackPlugin 不是构造函数

c# - 使用 TransactionScope 和 SqlCommand 保持数据库同步

c# - 在 C# 中使用 Javascript 序列化器将 DataTable 转换为嵌套 JSON

c# - Moq 与 Autofac Func<Owned<IClass>>

c# - Asp.net Core 中的 HttpRequestException : An error occurred when retrieving Google user information (Forbidden).

.net-core - 我们可以在基于 Linux 的操作系统中使用位框架吗?

c# - 升级到 Core 2 Preview 2 后获取 "Could not resolve a service of type .."