c# - 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所在的表达式块中的参数。但是上下文在 Startup.cs 的其他任何地方都没有显示,当我注释掉时编译器似乎并不介意
using Microsoft.AspNetCore.Mvc;
.Net 是否在幕后透明地做一些事情来为 options.CheckConsentNeeded 提供上下文,如果我要手动编写该语句,我怎么知道上下文可用以及它来自哪里?
解决方案
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。
推荐阅读
- c - Is it worse in any aspect to use the CMPXCHG instruction on an 8-bit field than on a 32-bit field?
- android - 无法访问 Android Q 中的存储空间
- powershell - POWERSHELL RDP 文件打开
- java - 如何将导出的 java 对象的格式更改为文件?
- javascript - 在 APEX 中获取主题滚轮配置 JSON
- ios - 在 spritekit 中沿 UIBezierPath 绘制节点
- mysql - 如何提高 MySQL 存储过程运行 20 秒
- java - 如何过滤和限制 LDAP 中组对象的属性
- python - 为 json 文件进行正确的输入
- node.js - Firebase - 从两个数组中过滤数据