在.NET核心应用程序的中间件中,我使用HttpContext
来保存cookie的值,如下所示:
app.Run(async context =>
{
// context.Response.Cookies.Append("se_id","5");
if(context.Request.Cookies["se_id"] == 5){
context.Items["isVerified"] = true;
}
await _next.Invoke(context);
});
然后在函数中,我试图使用以下方法检查它:
bool v = HttpContext.Items["isVerified"] == true;
if (v){
Console.WriteLine("Verified request? {0}", HttpContext.Items["isVerified"]);
}
else{
Console.WriteLine("NOT Verified request? {0}", HttpContext.Items["isVerified"]);
}
它给了我编译错误:
运算符'=='不能应用于'object'类型的操作数和'bool'[netcoreapp1.1]获取执行操作的Microsoft.AspNetCore.Http.HttpContext。 HttpContext ControllerBase.HttpContext
我可以通过在我定义为的中间件中重新定义它来解决它:
context.Items["isVerified"] = "true";
然后在函数中检查它:
bool v = HttpContext.Items["isVerified"].ToString() == "true";
有没有办法避免将其用作Boolean
,而不是强制将其转换为双方的text
。
答案 0 :(得分:2)
就这样使用它:
if ((bool)HttpContext.Items["isVerified"])
Console.WriteLine("Verified request? {0}", HttpContext.Items["isVerified"]);
else
Console.WriteLine("NOT Verified request? {0}", HttpContext.Items["isVerified"]);
但请注意,如果HttpContext.Items["isVerified"]
为null