Hasan A Yousef Hasan A Yousef - 1 year ago 87
C# Question

Compare HttpContext with Boolean i

In my middleware in the .NET core app, I've use the

to save the value of the cookie, as below:

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);

Then in the function, i'm trying to check it using:

bool v = HttpContext.Items["isVerified"] == true;
if (v){
Console.WriteLine("Verified request? {0}", HttpContext.Items["isVerified"]);
Console.WriteLine("NOT Verified request? {0}", HttpContext.Items["isVerified"]);

It gave me the compilation error:

Operator '==' cannot be applied to operands of type 'object' and 'bool' [netcoreapp1.1] Gets the Microsoft.AspNetCore.Http.HttpContext for the executing action. HttpContext ControllerBase.HttpContext

I can solve it by redefining it in the middleware I defined it as:

context.Items["isVerified"] = "true";

then check it in the function by:

bool v = HttpContext.Items["isVerified"].ToString() == "true";

Is there a way to avoid use it as
instead of being forced to convert it to
in both sides.

Answer Source

Just use it like so:

if ((bool)HttpContext.Items["isVerified"])
    Console.WriteLine("Verified request? {0}", HttpContext.Items["isVerified"]);
    Console.WriteLine("NOT Verified request? {0}", HttpContext.Items["isVerified"]);

But keep in mind that this will not protect you against null ref exception if HttpContext.Items["isVerified"] is null

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download