Yehia A.Salam
Yehia A.Salam

Reputation: 2028

Calling WebService From Same Project

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?

Upvotes: 1

Views: 3187

Answers (3)

Aaronaught
Aaronaught

Reputation: 122684

Instead of depending exclusively on the HttpContext in your web service (not generally a good practice), you should add a parameterized constructor to your WebService class. Then, in the default parameterless constructor, you can check the HttpContext for 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, use Server.MapPath to locate it.

Or you can create an interface abstraction, say IPathMapper, with one implementation that wraps Server.MapPath and 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.

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115548

Yes you do, because the request is going out and back into the solution through the web interface.

Upvotes: 0

Tom Cabanski
Tom Cabanski

Reputation: 8018

Yes, if you want to use the HTTP Context, the call has to come in from the web (via a web reference as you suggest).

Upvotes: 0

Related Questions