title: Can't create cookie, getting "Headers are read-only, response has already started" in asp.net core (razor pages)
body: <p>I'm trying to set a cookie, but I get "Headers are read-only, response has already started."</p>
  
  <p>The method that write the cookie is in a property returning an User object in Utility.cs and Gallery.cshtml invokes the property (<em>img.UserVoteExists(_util.User)</em>) through the Utility object thats defined in ViewImports</p>
  
  <p><strong>Utility.cs</strong>:</p>
  
  <pre><code>public User User
  {
      get
      {
          User result = new User();
  
          if (this.Context.Request.Cookies.ContainsKey(UserCookieName))
          {
              result = JsonConvert.DeserializeObject&lt;User&gt;(this.Context.Request.Cookies[UserCookieName]);
          }
          else
          {
              result = JsonConvert.DeserializeObject&lt;User&gt;(InvokePost("CreateUser", new CreateUserContextModel() { User = result }).Result);
          }
  
          this.Context.Response.Cookies.Append(UserCookieName, JsonConvert.SerializeObject(result), new CookieOptions() { Expires = DateTime.Now.AddDays(120) });
  
          return result;
      }
  }
  </code></pre>
  
  <p><strong>_ViewImports.cshtml</strong>:</p>
  
  <pre><code>@inject IUtility _util
  </code></pre>
  
  <p><strong>Gallery.cshtml</strong>:</p>
  
  <pre><code>&lt;div id="images" class="images-wrap list-small"&gt;
      @foreach (Image img in Model.CurrentItem.Images)
      {
          &lt;div class="item-wrap" data-index="@img.Index" data-filename="@img.Filename"&gt;
              &lt;img src="/IMAGES/Gallery/Items/@Html.Raw(Model.Name.ToCamelCase() + "/Thumb/" + img.Filename)" class="img-fluid item" /&gt;
              &lt;div class="info-wrap"&gt;
                  &lt;div class="header-wrap"&gt;
                      &lt;div class="vote-wrap"&gt;
                          &lt;div class="circle clickable @Html.Raw(img.UserVoteExists(_util.User).AppendIfTrue("d-none"))"&gt;
                              &lt;lc:fa name="thumbs-up" prefix="far" class="icon" /&gt;
                          &lt;/div&gt;
                          &lt;div class="circle @Html.Raw(img.UserVoteExists(_util.User).AppendIfFalse("d-none"))"&gt;
                              &lt;lc:fa name="thumbs-up" prefix="fas" class="icon" /&gt;
                          &lt;/div&gt;
                      &lt;/div&gt;
                      &lt;div class="caption-wrap"&gt;
                          &lt;h2 class="caption"&gt;@img.Name&lt;/h2&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
  
                  &lt;p class="description-wrap"&gt;
                      &lt;span class="caption"&gt;@Html.Raw(img.Description)&lt;/span&gt;
                  &lt;/p&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      }
  &lt;/div&gt;
  </code></pre>