title: How to use session in apicontroller in asp.net mvc 4
body: <p>I am working on an application using <code>asp.net mvc 4</code>. Here I want to use autocomplete extender using <code>JQuery</code> where i want to populate all location of that <code>CityID</code> which is stored in session. </p>
  
  <p><strong>Here is the function for creating the session:</strong></p>
  
  <pre><code>public string Create(string City)
  {
      try
      {
          //HttpSessionStateBase Session["c"]=City;
          //HttpContext.Current.Session["City"] = City;
          System.Web.HttpContext.Current.Session["City"] = City;
          long CityID = Convert.ToInt64(System.Web.HttpContext.Current.Session["City"].ToString());
  
          return City;
      }
      catch (Exception ex)
      {
         throw (ex);
      }
  }
  </code></pre>
  
  <p>This function is called when user select any city from the City <code>dropdownlist</code>.</p>
  
  <p><strong>My <code>JQuery</code> calling for autocomplete extender is:</strong> </p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  var url = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "ProductApi" })';
  $('#txtLocation').autocomplete({
      source: function (request, response) {
          alert(url);
          $.ajax({
              url: url,
              data: { query: request.term },
              dataType: 'json',
              type: 'GET',
              success: function (data) {
                  response($.map(data, function (item) {
                      return {
                          label: item.Name
                          //value: item.ID
                      }
                  }));
              }
          })
      },
      select: function (event, ui) {
          $('#txtLocation').val(ui.item.label);
          //$('#ID').val(ui.item.value);
          return false;
      },
      minLength: 1
  });
  </code></pre>
  
  <p></p>
  
  <p><strong>My api controller is :</strong></p>
  
  <pre><code>public class ProductApiController : ApiController
  {
      SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLCONN"].ToString());        
  
      [HttpGet]
      public IEnumerable&lt;Search&gt; GetProducts(string query = "")
      {
          cnn.Open();
          //string gid = GETSession("t");
  
          long CityID = Convert.ToInt64(System.Web.HttpContext.Current.Session["City"].ToString());
  
          SqlCommand cmd = new SqlCommand("Check_PrefixText", cnn);
          cmd.Parameters.AddWithValue("City", CityID);
          cmd.Parameters.AddWithValue("@Prefix", query);
  
          cmd.CommandType = CommandType.StoredProcedure;
  
          SqlDataAdapter da = new SqlDataAdapter(cmd);
          DataTable dt = new DataTable();
          da.Fill(dt);
  
          //var result = IEnumerable&lt;City&gt;(query);
          Search obj = new Search();
          cnn.Close();
          return dt.AsEnumerable().Select(row =&gt;
          {
              return new Search
              {
                  Name = Convert.ToString(row["Name"]),
              };
          });
      }
  }
  </code></pre>
  
  <p><strong>In <code>Global.asax</code> file i have written 2 methods:</strong></p>
  
  <pre><code>protected void Application_PostAuthorizeRequest()
  {
      if (IsWebApiRequest())
      {
          HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
      }
  }
  
  private bool IsWebApiRequest()
  {
      return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
  }
  </code></pre>
  
  <p><strong>In <code>webApiConfig</code> Class i have written as follows:</strong> </p>
  
  <pre><code>public static string UrlPrefix { get { return "api"; } }
  public static string UrlPrefixRelative { get { return "~/api"; } }
  
  public static void Register(HttpConfiguration config)
  {
      config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
      );
  }
  </code></pre>
  
  <p>But still the value of <code>session["City"]</code> is coming <strong>null</strong> in <code>ApiController</code> while there there is value stored showing in <code>session["City"]</code>.</p>