Reputation: 4872
I have created a MVC application and added new WebApi controller in it called ReportsApiController. And i created a session called Session["ReportId"]=5 in application and tried to access from web Api method but it is throwing null reference exception. I am accessing the WebApi using $.getJASON method.Let me know how can i get it resolved.
Upvotes: 0
Views: 820
Reputation: 1039130
Yes, you can if the Web API is hosted in the same web application that stored the value in the session:
HttpContext.Current.Session
But you should not do it. This violates the stateless nature of the Web API. If you need to pass some information to this API, don't make it depend on some session state. Pass this information under the form of a model. Or if you don't want to pass complex data, simply persist this information in some common datastore (could be a database for example) and then only pass the id to the Web API so that it retrieves the value from the datastore.
Upvotes: 3
Reputation: 75316
Think out of the box, Web API is STATELESS service, so Session stuff will not suit anymore, it is not like ASP.NET web form which simulates stateful website with Session, ViewState.
Depend on your case, but you can use MemoryCache
instead if you want to cache something.
Upvotes: 1