Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor read/write cookies using IHttpContextAccessor

$
0
0

So I have some problems using the IJSRuntime invoker to write and read cookies in Blazor using JavaScript. After some research, I found a guide to use the IHttpContextAccessor to read and write cookies using the HttpContext: https://www.c-sharpcorner.com/article/asp-net-core-working-with-cookie/

This is my current setup:

Startup.cs

public void ConfigureServices (IServiceCollection services) {    ...    services.AddHttpContextAccessor();}

Index.razor

@inject IHttpContextAccessor HttpContextAccessor@code {    private CookieController m_CookieController;    protected override async Task OnInitializedAsync () {        m_CookieController = new CookieController(HttpContextAccessor); // Set HttpContextAccessor for setting and getting cookies    }}

CookieController

public class CookieController {    private readonly IHttpContextAccessor m_HttpContextAccessor;    public CookieController (IHttpContextAccessor httpContextAccessor) {        m_HttpContextAccessor = httpContextAccessor;    }    public void SetCookie (String cookieName, String value, Int32? expireTime) {        CookieOptions option = new CookieOptions();        if (String.IsNullOrEmpty(cookieName)) {            return;        }        if (expireTime.HasValue) {            option.Expires = DateTime.Now.AddMinutes(expireTime.Value);        } else {            option.Expires = DateTime.Now.AddDays(1);        }        if (m_HttpContextAccessor.HttpContext.Response != null) {            if (String.IsNullOrEmpty(value)) {                value = "null";            }            m_HttpContextAccessor.HttpContext.Response.Cookies.Append(cookieName, value, option);            return;        }    }    public String ReadCookie (String cookieName) {        if (String.IsNullOrEmpty(cookieName)) {            return null;        }        if (m_HttpContextAccessor.HttpContext.Request != null && !String.IsNullOrEmpty(m_HttpContextAccessor.HttpContext.Request.Cookies[cookieName])) {            return m_HttpContextAccessor.HttpContext.Request.Cookies[cookieName];        }        return null;    }}

So my problem here is that whenever I call m_CookieController.SetCookie(), I get the following exception:

System.InvalidOperationException: "The response headers cannot be modified because the response has already started."

What is wrong here, and how can I fix this?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>