Home > Software engineering >  ASP.NET Core 6: problems with HttpContext
ASP.NET Core 6: problems with HttpContext

Time:11-22

I wrote the following public method:

 public IList<CookieType> GetAcceptedCookieTypes(HttpContext httpContext)
        {
            var result = new List<CookieType>();
            // accepted by default
            result.Add(CookieType.Essential);

            var cookie = httpContext.Request.Cookies["cc_cookie_accept"];
            if (cookie != null)
            {
                var arrVal = cookie.Split('.');
                if (arrVal != null && arrVal.Length > 1)
                {
                    var arrCheck = arrVal[1];
                    if (arrCheck.Length > 0 && arrCheck[0] == '1')
                    {
                        result.Add(CookieType.Statistical);
                    }
                }
            }
            return result;
        }

I have multiple places where the method gets consumed, but I keep getting this error since I had to add the HttpContext httpContext:

Error CS7036 There is no argument given that corresponds to the required formal parameter 'httpContext' of 'GDPRScript.GetAcceptedCookieTypes(HttpContext)

I tried consuming it like this:

var _httpContext = HttpContext httpContext;
types = GetAcceptedCookieTypes(_httpContext);

But then it throws 3 errors on the definition of _httpContext (value) them being: CS0103, CS0201, CS1002

  • How can I properly fix this?

CodePudding user response:

You need to pass the HttpContext that is... well, in your context. Since you did not explain what your context of calling this method is, you will need to find that yourself:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0

In this link, there is a list how to get your HttpContext depending on what technology you use. ASP.NET Core is a wide field of technologies or ways to call or be called and the way to get a HttpContext varies slightly in each.

If you are not directly calling this in your controller, this might be your way of getting a HttpContext via Dependency injection in any component.

  • Related