Vladimir
Vladimir

Reputation: 1797

ASMX Web Service Problem Communicating with Windows Service In a Separate Thread

There is a Windows Service on Windows Server 2003 (Amazon Virtual Machine). Some applications can communicate with it (using pipes, but there is an wrapper to do it). It is tested and it works. Also, there is a Web Service written in C# (ASP.NET) which communicates with mentioned Windows Service. When Web Method is called, it creates an instance of the class and calls a function - the function "connects" to Windows Service and post a job to it. But, if inside Web Method is created a thread and the function which "connects" to Windows Service is called inside a thread - connection fails. Connection to Windows Service uses pipes. Web Service works on IIS7. It is worth to mention that all works on my local machine, either from debugger (local server started by VS 2010) or from IE when I call Web Method on Web Service which works on local IIS7. In local all works - but on Amazon Instance doesn't. I'm not a web programmer, so I think there is some issue with security. Any hint? Thanks.

EDIT: Uwe's comment reminded me - the Web Method at first tries to download some files using http and it saves them to path C:\intetpub\wwwroot\files\". It works if files are downloaded from the web method, but download fails if it is done from another thread created in Web Method. Exception was: Access is denied. So, I changed security settings on mentioned folder and explicitly allowed user created by IIS7 (IIS_IUSRS) to read/write the folder, and now files can be downloaded. It seems that the source of these problems is the same.

EDIT: The solution is moved to an answer on Will's suggestion.

Upvotes: 3

Views: 1219

Answers (1)

Vladimir
Vladimir

Reputation: 1797

Ok guys, the solution is found and as Will recomends, I'll post it here, as an answer to my own question. So, the solution:

The problem was because the thread created by Web Method has to be impersonated. So, in the caller method I had to something like:

[WebMethod]
public void Fnc()
{
    ...
    ...
    System.Security.Principal.WindowsIdentity wi =    System.Security.Principal.WindowsIdentity.GetCurrent();
    System.Threading.Thread postJobThread = new Thread(PostJobThread);
    postJobThread.Start(wi);
    ...
}

...

private void PostJobThread(object ob)
{
    System.Security.Principal.WindowsIdentity wi = (System.Security.Principal.WindowsIdentity)ob;
    System.Security.Principal.WindowsImpersonationContext ctx = wi.Impersonate();

    ...
    // Do some job which couldn't be done in this thread
    ...
    // OK, job is finished
    if(ctx != null)
    ctx.Undo();
}

That's all. Thanks to guys who commented my question and I hope it'll be useful for somebody else.

Upvotes: 2

Related Questions