问题
I have a .Net application that uses Forms Authentication mode and has a function that calls an asynchronous task. Below is the snippet of the task:
Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);
The thread is working fine when I test in on the Visual Studio IDE. The issue is when I deploy it, the threading task seems to be skipped or not executed by the system.
I've read an article that this can be caused by permissions in IIS:
http://codemine.net/post/Thread-Not-working-in-Aspnet-When-deployed-to-IIS
Tweaking the solution on above article to be implemented in Forms authentication, below is the code for that:
[System.Runtime.InteropServices.DllImport("advapi32.dll", EntryPoint = "LogonUser")]
private static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
public JsonResult uploadimages(){
try{
IntPtr token = new IntPtr(0);
token = IntPtr.Zero;
bool returnValue = LogonUser("Administrator", "WIN-82CH4949B3Q", "Neuron14",
3,
0,
ref token);
WindowsIdentity newId = new WindowsIdentity(token);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
var task2 = Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);
impersonatedUser.Undo();
return Json(new { message = "Success" }, "text/plain; charset=utf-8");
}
catch (ex Exception)
{
return Json(new { error= ex.Message }, "text/plain; charset=utf-8");
}
}
Implementing the above code to the system still does not execute the thread once deployed in IIS. I'm really having a hard time fixing this since I do not really know why the thread is not executing when deployed.
回答1:
There is a problem when you attempt to impersonate a windows identity:
WindowsIdentity newId = new WindowsIdentity(token);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
var task2 = Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);
impersonatedUser.Undo();
The problem is that the Impersonate
function only applies for that thread, and your UploadFunction
is running on a different thread.
Here's a modification to your code which has the Impersonate
method called on the background task's thread:
WindowsIdentity newId = new WindowsIdentity(token);
var task2 = Task.Factory.StartNew(() =>
{
using(WindowsImpersonationContext wi = newId.Impersonate())
{
UploadFunction();
}
},
tokenSource.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default
);
My guess is that it worked on your local machine because you were uploading to a folder which allowed anonymous access. The permissions on your production server would be much tighter.
来源:https://stackoverflow.com/questions/25989420/threading-task-not-executing-in-iis