Startup.cs中的C#HttpContext上下文来自哪里



所以我发现了这个RazorPages示例代码

using Microsoft.AspNetCore.Mvc;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

我的问题是,上下文来自哪里?我在看

options => { ... } 

作为一个匿名委托函数,lambda运算符左侧的部分为options,它是输入到context所在的表达式块中的参数。但是context在Startup.cs中没有显示在其他任何位置,编译器似乎也不介意我注释掉

using Microsoft.AspNetCore.Mvc;

.Net是否在幕后透明地为选项提供上下文。CheckConsentNeed,如果我手写该声明,我如何知道上下文可用,以及它来自哪里?

Configure允许您传入lambda来配置选项。看看这个人为的例子来解释正在发生的事情。

// we have an options class that will hold all the props to configure
// our coolie policy
public class Options
{
public bool UseConsent { get; set; }
}
// this emulates the signature for services.Configure. It takes a lambda
// and simply executes it, enabling the caller to manage the settings
public static void Configure(Action<Options> callback)
{
//create new options instance
var options = new Options();
// allow caller to access this instance and set properties
callback(options);
Console.WriteLine(options.UseConsent); // this will print true
}

public static void Main()
{
Configure(options =>
{
options.UseConsent = true;
});
Console.ReadLine();
}

正如您所看到的,任何地方都没有魔法发生,您之所以可以设置选项或不设置选项,是因为Configure过载,允许您传入或不传入lambda。

CheckConsentNeeded属性接受Func<HttpContext, bool>的委托。

C#中的Func<HttpContext, bool>可以表示采用HttpContext的参数并返回bool值的方法。

bool MyFunction(HttpContext context)
{
}

在您的案例中,您为属性指定了一个lambda表达式,context表示类型为HttpContext的参数。context是一个名称,您可以将其更改为其他名称,如ctxc等。

使用context不需要添加using,但如果在代码中使用其类型HttpContext,则必须使用using

允许在命名空间中使用类型

在运行时,当委托的调用者(很可能在中间件中(调用委托时,它将把HttpContext的实例作为参数传递给分配给CheckConsentNeeded属性的委托。

相关内容

最新更新