Friday 23 March 2012

MVC 4 Web API access Session

It's not recommended to use Session  in Web API for various of good reasons. However, in case you're still so interested to access Session for any business needs, here is a quick solution to allow accessing Session in Web API.

 
// In global.asax
public class MvcApp : System.Web.HttpApplication
{
 public static void RegisterRoutes(RouteCollection routes)
 {
  var route = routes.MapHttpRoute(
   name: "DefaultApi",
   routeTemplate: "api/{controller}/{id}",
   defaults: new { id = RouteParameter.Optional }
  );
  route.RouteHandler = new MyHttpControllerRouteHandler();
 }
}

// Create two new classes
public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
{
 public MyHttpControllerHandler(RouteData routeData): base(routeData)
 {
 }
}
public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
 protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
 {
  return new MyHttpControllerHandler(requestContext.RouteData);
 }
}

// Now Session is visible in your Web API
public class ValuesController : ApiController
{
 public string GET(string input)
 {
  var session = HttpContext.Current.Session;
  if (session != null)
  {
   if (session["Time"] == null)
    session["Time"] = DateTime.Now;
   return "Session Time: " + session["Time"] + input;
  }
  return "Session is not availabe" + input;
 }
}
 



Source is here.

55 comments:

  1. Great post. I know it's bad to use session in ApiController but I had to. Thank you so much!

    ReplyDelete
  2. Do you have a version of this for the mvc 4 web api rc
    Thanks for your time.

    ReplyDelete
  3. I'd also need to know if it's possible with the latest version, thanks.

    ReplyDelete
  4. Thank you for the article. But it doesn't work with Web API in ASP.NET 4.5.

    in WebApiConfig.cs, route is of type IHttpROUT which doesn't have RouteHandler!

    ReplyDelete
  5. how to use correct way session in web api???

    ReplyDelete
  6. Have you really tested it ? or just copied and pasted stuff from some place ?

    ReplyDelete
  7. Solution for ASP.NET 4.5: http://stackoverflow.com/questions/16626820/asp-net-mvc-web-api-4-5-session-state

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Session state works fine in MVC4 WebAPI by implementing above logic for single user.
    But for other users session state is never maintained and always returns null.
    Any suggestions...???

    ReplyDelete
  10. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects. Dot Net Training in chennai | Dot Net Training in velachery

    ReplyDelete
  11. Thanks for your valuable post... The data which you have shared is more informative for us...
    xiaomi service centre chennai

    ReplyDelete
  12. Hi, It’s Amazing to see your blog.This provide us all the necessary information regarding
    upcoming real estate project which having all the today’s facilities.
    autocad in bhopal
    3ds max classes in bhopal
    CPCT Coaching in Bhopal
    java coaching in bhopal
    Autocad classes in bhopal
    Catia coaching in bhopal

    ReplyDelete
  13. Vanskeligheter( van bi ) vil passere. På samme måte som( van điện từ ) regnet utenfor( van giảm áp ) vinduet, hvor nostalgisk( van xả khí ) er det som til slutt( van cửa ) vil fjerne( van công nghiệp ) himmelen.

    ReplyDelete
  14. Hey There! Check out the best 10 consulting website examlpes here! Consulting website examples:)

    ReplyDelete
  15. Các dịch vụ của nội thất Đăng Khôi bao gồm: sửa đồ gỗ, làm gác xép, sửa sàn gỗ...

    ReplyDelete
  16. Thanks for sharing it.I got Very significant data from your blog.your post is actually Informatve .I'm happy with the data that you provide.thanks

    click here
    see more
    visit us
    website
    more details

    ReplyDelete
  17. Thanks for your excellent blog and giving great kind of information. So useful. Nice work keep it up thanks for sharing the knowledge.
    Visit us
    Click Here
    For More Details
    Visit Website
    See More

    ReplyDelete
  18. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve. I got Very valuable information from your blog.I’m satisfied with the information that you provide for me.

    Python training in Pune
    Python Classes in Pune
    Python Courses in Pune
    Python Institute Pune



    ReplyDelete
  19. It is important to note here that almost all companies extend the sale up to Cyber Monday. Black Friday is America’s biggest annual holiday shopping frenzy which usually attracts a lot of sales. Black Friday Web Hosting Deals 2019 sale is on November 29, 2019, and if you are on the lookout to grab the best deals at affordable prices, don’t miss out this Black Friday.

    ReplyDelete
  20. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informative.I’m satisfied with the information that you provide for me.Nice post. By reading your blog, i get inspired and this provides some useful information.

    sap mm training in pune with placement

    ReplyDelete
  21. Hi, This is your awesome article , I appreciate your effort, thanks for sharing us.
    cism training
    cism certification

    cisa training,
    cisa certification
    cisa exam

    ReplyDelete
  22. Great post i must say and thanks for the information. Education is definitely a sticky subject. I appreciate your post and look forward to more.

    python online course certification

    ReplyDelete
  23. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the AWS Cloud Practitioner Online Training

    ReplyDelete

  24. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

    Data Scientist Course in pune

    ReplyDelete
  25. Hi to everybody, here everyone is sharing such knowledge, so it’s fastidious to see this site, and I used to visit this blog daily. ExcelR Data Science Courses

    ReplyDelete
  26. If it's not too much trouble share more like that. ExcelR Data Analytics Courses

    ReplyDelete
  27. Digibrom is the Best Digital Marketing Training & Services in Bhopal, providing complete digital growth for your business. We are one of the leading Digital Marketing company in Bhopal, and we are experts in digital marketing & web design. The market penetration along with the use of digital technology is our power. We serve businesses according to the need and requirements of the customers and deliver quality work in time because Digibrom is the best digital marketing training institute and service provider. We create likable content that increases the time spent by the customer on the internet.
    Digital marketing Training in bhopal

    ReplyDelete
  28. Keep your eyes on your data so that you don't lose anything. You can take service from Fungible. They will take care of your all data. They are a technology-based company that is founded in 2015. Visit their site to get more info.

    ReplyDelete
  29. Nice article
    Visit Tech News to get tips and tricks of Technology, Android, Websites and others.

    ReplyDelete
  30. Statistics students and professor are worried to find the deviation calculator because their work depends on it. guardians of the galaxy star lord game jacket

    ReplyDelete
  31. It's actually a great and helpful piece of information. I am satisfied that you just shared this useful information for us. Good For Health Bad For Education Jacket

    ReplyDelete
  32. best industrial training in amritsar
    <a href="https://www.bmninfotech.com/industrial-training/>web development internship</a>

    ReplyDelete
  33. Very Nice Article..

    Personal loan for CIBIL defaulter: Vintage Finance made new possibilities for personal loan for CIBIL defaulters in Delhi. Persons with a low CIBIL score can have nightmares getting their loans approved. One can get a bad CIBIL score because of at least one of the accompanying reasons.

    ReplyDelete
  34. I like your Post.. Keep it up

    3D Wheel Alignment Machine: Sarv specializes in 3D wheel Alignment Machines for passenger Car &LCV workshops. Using the latest 3D camera technology, Sarv machines provide accurate readings.

    Tubeless Tyre Repair Kit
    Wheel Balancing Machine
    Automatic Tyre Inflator

    ReplyDelete