1

I need to send an information to a user via a web-api only once by session, and I used to do in asmx by storing a variable in the session.

As in web-api I can't use sessions, how can I do this ?

haim770
  • 48,394
  • 7
  • 105
  • 133
gobes
  • 507
  • 7
  • 25

1 Answers1

4

Started as a comment, but ended up being too long...

ASP.NET Web API is mainly used to create HTTP services and, as Microsoft claim, ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. Such services are meant to be stateless so what you're trying to do is technically going against a pretty fundamental design goal. Having said that, things are not as clear-cut as they seem and there's some (almost religious) debate over whether a REST service should be stateless or allow state in some degree.

The following SO questions might give you some help and/or direction about achieving what you want:

Also, the following StrathWeb article gives some additional advice (with a code example) and links to other sources of information:

In a project I'm currently working on, I'm having to store some state information for token-based user authentication and, since I have access to a database, I use a table to store the information I need. Technically speaking, and certainly for some people, I'm breaking the rules. But it works for me and, at the end of the day, you have a job to do and you may not always have the time to do things 100% correctly, so you have to be pragmatic in your approach.

Community
  • 1
  • 1
djikay
  • 10,450
  • 8
  • 41
  • 52
  • I am aware that webapi are for restful services, so sessions don't have to be handled... but when you have to be sure the same data is not send twice during the same session, well, you have to keep a state somezwhere; and in the end I used sessions. But maybe there is a better way to achieve this ? – gobes Jun 20 '14 at 07:35
  • The last link from StrathWeb has a code example on how to enable session support similar to MVC, so you should definitely investigate it. Alternatively, if you have access to a database, you could add a "Session" table and log sessions against users, possibly with an expiry date/time among other things you need to keep in your session. Finally, if you don't care about persistence between server reboots, you could do this with an application-wide collection object, although that wouldn't be a good idea if you have thousands of sessions since the whole thing would require lots of memory. – djikay Jun 20 '14 at 09:25
  • My comment wasn't clear, I enabled sessions in my webservice. If the only solution is to keep the data in a dedicated table, I'll definitely use sessions. – gobes Jun 20 '14 at 10:22