Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Mar 20, 2012 08:14 AM by mastoj
Mar 19, 2012 11:05 PM|LINK
How do you access Current HttpContext in a MediaTypeFormatter? It is working if I inherit from the BufferedMediaTypeFormatter, but if I inherit the MediaTypeFormatter HttpContext.Current is null. Is there a way around that?
Mar 19, 2012 11:12 PM|LINK
It is recommened that you don't access HttpContext within WebApi. If you are trying to store data that should persist over the entirety of a request, then use the HttpRequestMessage properties collection.
What type of data are you trying to obtain from the context?
Mar 19, 2012 11:21 PM|LINK
I am just playing around preparing a demo on web api and wanted an easy way to store files and control of where I stored them within my application. So I was trying to do a Server.MapPath operation basically. Is there a new recommended way to do that?
Mar 19, 2012 11:57 PM|LINK
I don't see a straight forward way of getting at this data. Off the top of my head, there are a lot of different ways to solve this within Global.asax. One way is to access the request and get the relevant path info from the global.asax begin request handler
and then store it in the HttpConfiguration properties bag (GlobalConfiguration.Configuration.Properties). Later in the pipeline, you can open up the configuration properties and retrieve this value.
While this is not meant to be exposed, you can access the http context via request.Properties["MS_HttpContext"], I wouldn't use this in production but for demo purposes it might work for you.
Mar 20, 2012 07:12 AM|LINK
wanted an easy way to store files and control of where I stored them within my application. So I was trying to do a Server.MapPath operation basically
For media type formatters, especially those that write types, (for me) it's all about data preparation. I.e. the resource (or model) type that is written out by your media type formatter should be pre-prepared with all the data it needs earlier on in the
processing pipeline. So you could, for example, do the Server.MapPath in your controller, and store the resulting path in the resource/model type that the media type formatter will operate on.
Mar 20, 2012 08:14 AM|LINK
Thank you for your answer, it is definitely an option.