I’m trying to call an asp.net webservice from the same project it’s in:
[MethodImpl(MethodImplOptions.Synchronized)]
public static void OnFileCreated(object source, FileSystemEventArgs e) {
trackdata_analyse rWebAnalyse = new trackdata_analyse();
rWebAnalyse.Analyse(@"pending\" + e.Name, "YOUNIVATE");
}
However i always get the following “HttpContext is not available. This class can only be used in the context of an ASP.NET request.” when calling Server.MapPath from the webservice:
[WebMethod]
public int Analyse(string fileName, string PARSING_MODULE){
int nRecords;
TrackSession rTrackSession = new TrackSession() ;
string filePath = Server.MapPath(@"..\data\") + fileName;
Do i have to add the WebReference instead, though the webservice is in the same project?
Instead of depending exclusively on the
HttpContextin your web service (not generally a good practice), you should add a parameterized constructor to yourWebServiceclass. Then, in the default parameterless constructor, you can check theHttpContextfor the same dependencies.That way, when you need to invoke the web service from the same assembly, you can share dependencies in-process instead of relying in the
HttpContext.In this case your dependency is
Server.MapPath, which maps a relative path in a URL to a physical path on the hard drive. You can adjust your web service to accept a specific path or base path instead, and when none is supplied, useServer.MapPathto locate it.Or you can create an interface abstraction, say
IPathMapper, with one implementation that wrapsServer.MapPathand another that just wraps a physical path, and use the second one from within the same assembly.I’d really recommend this over adding a web reference from within your web service assembly; the latter is going to significantly hurt performance, not to mention making your service app more difficult to maintain.