Specifically, Session variables. I have an .ashx in my ASP.NET MVC project that is pulling some image data to display to a user, and I need to be able to access an object that I've stored in the session. From controllers I can pull the object fine, but in my ashx page, the context.Session is null. Any thoughts? Thanks!
Here is an example of what I'm trying to do... context.Session is always returning null.
private byte[] getIconData(string icon) { //returns the icon file HttpContext context = HttpContext.Current; byte[] buffer = null; //get icon data if ( context.Session["tokens"] != null) { //do some stuff to get icon data } }
ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically: public Task Invoke(HttpContext context) { // Do something with the current HTTP context... }
The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.
The IHttpContextAccessor is an interface for . Net Core for accessing HttpContext property. This interface needs to be injected as dependency in the Controller and then later used throughout the Controller.
You must import the System.Web assembly in your code and then you can do something like this:
HttpContext context = HttpContext.Current; return (User)context.Session["User"];
Editing:
Dude, I did some tests here and it works for me, try something like this:
Create a helper class to encapsulate you getting session variables stuff, it must import the System.Web assembly:
public class TextService { public static string Message { get { HttpContext context = HttpContext.Current; return (string)context.Session["msg"]; } set { HttpContext context = HttpContext.Current; context.Session["msg"] = value; } } }
Then in your controller you should do something like:
TextService.Message = "testing the whole thing"; return Redirect("/home/testing.myapp");
And in your other classes you can call the helper class:
return TextService.Message;
Give it a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With