c# - How to access TempData in my own utility class? Or TempData is null in constructor -
i use tempdata in of views/actions i'd extract class. problem if try create class in controller's constructor, tempdate there null. better yet, i'd have class injectable controller. need access tempdata when class created.
so how can tempdata constructed in separate class?
this asp.net core 2.0 web app.
you can access temp data anywhere injecting itempdatadictionaryfactory
need it. can call gettempdata
returns itempdatadictionary
can use access (read or write) temp data current http context:
public class exampleservice { private readonly ihttpcontextaccessor _httpcontextaccessor; private readonly itempdatadictionaryfactory _tempdatadirectionaryfactory; public exampleservice(ihttpcontextaccessor httpcontextaccessor, itempdatadictionaryfactory tempdatadictionaryfactory) { _httpcontextaccessor = httpcontextaccessor; _tempdatadictionaryfactory = tempdatadictionaryfactory; } public void dosomething() { var httpcontext = _httpcontextaccessor.httpcontext; var tempdata = _tempdatadictionaryfactory.gettempdata(httpcontext); // use tempdata usual tempdata["foo"] = "bar"; } }
btw. reason why tempdata
null
in controller’s constructor because controller context injected after controller has been created (using property injection). when controller’s constructor runs, there isn’t information current request yet.
if inject service though, , service works exampleservice
above, work within constructor, since request necessary information di container (the factory , http context).
Comments
Post a Comment