且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Cookie 和 ASP.NET 核心

更新时间:2022-02-04 04:03:22

对于在应用程序中手动创建的通用 cookie,您可以在创建时控制安全标志 - 例如:

For a general cookie manually created within your application, you control the flags for security when creating it - for example:

Response.Cookies.Append(
    "COOKIE_NAME",
    "COOKIE_VALUE",
    new CookieOptions()
    {
        Path = "/",
        HttpOnly = false,
        Secure = false
    }
);

此处,将 HttpOnly 设置为 true 将阻止客户端 JS 访问 cookie vlaue,而将 Secure 设置为 true 将仅允许通过 HTTPS 提供/接收 cookie.

Here, setting HttpOnly to true would prevent client-side JS from accessing the cookie vlaue, and setting Secure to true would only allow the cookie to be served/received over HTTPS.

向响应添加 cookie 时不会应用任何默认值,如 ResponseCookies 类的源代码.

No defaults are applied when you add cookies to the response, as can be seen in the source code for the ResponseCookies class.

对于创建和使用自己的 cookie 的各种中间件(如您在回答中提到的 Session 中间件),它们可能有自己的配置选项,这些选项将控制它们自己创建的 cookie 的这些标志,但这将对您在应用程序其他地方创建的 cookie 没有任何影响.

For the various middlewares that create and consume their own cookies (like the Session middleware that you have mentioned in your answer), they may have their own configuration options that will control these flags for those cookies they create themselves, but this will make no difference to cookies you create elsewhere in your application.