title: Handling Session in async methods
body: <p>I am new to MVC5 and trying to implement sessions with in async methods in Controllers. I have created method like this</p>
  
  <pre><code>public async Task&lt;ViewResult&gt; Index()
  {
      string currentUserId = User.Identity.GetUserId();
      var userId = Convert.ToInt64(HttpContext.Session["UserId"]);
  
      var userDetail = await service.GetBy(currentUserId),
  }
  </code></pre>
  
  <p>This session thing, always fails with the following message</p>
  
  <blockquote>
    <p>Server Error in Application. Unable to cast object of type
    'System.Threading.Tasks.Task`1[System.Int64]' to type
    'System.IConvertible'.</p>
  </blockquote>
  
  <p>(Sorry, I am not able to post screenshot of actual error, as do not have enough reputation points on this site) </p>
  
  <p>I also tried to do it like this</p>
  
  <pre><code>var userId = await Task&lt;long&gt;.FromResult(Convert.ToInt64(HttpContext.Session["UserId"]));
  </code></pre>
  
  <p>and</p>
  
  <pre><code>var userId = await (Session["UserId"] as Task&lt;long&gt;);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>var userId = await Convert.ToInt64(HttpContext.Session["UserId"]);
  </code></pre>
  
  <p>But, it always gives the same message. Can somebody please point me to the correct approach. Also, if we can not use session with in async methods, then what would be the best solution for it.</p>