首页 > 解决方案 > 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 提供上下文,如果我要手动编写该语句,我怎么知道上下文可用以及它来自哪里?

标签: c#lambda.net-coreasp.net-core-mvcasp.net-core-2.0

解决方案


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。


推荐阅读