I created a WCF rest service, then called that from javascript using ajax. Now I want this service to be executed asynchronously, but it should also have access to session variables.
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/DoWork")]
void DoWork();
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
public void DoWork()
{
System.Threading.Thread.Sleep(15000); // Making some DB calls which take long time.
try
{
HttpContext.Current.Session["IsCompleted"] = "True"; // Want to set a value in session to know if the async operation is completed or not.
}
catch
{
}
}
}
Web.Config =
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<bindings>
<webHttpBinding>
<binding name="Rest_WebBinding">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="Rest">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="AsyncHost.Services.ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="AsyncHost.Services.ServiceBehavior" name="AsyncHost.Services.Service">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<endpoint behaviorConfiguration="Rest" binding="webHttpBinding" contract="AsyncHost.Services.IService" />
</service>
</services>
</system.serviceModel>
<system.web>
I consumed this service from javascript like as below,
$.ajax({
type: "POST",
async: true,
contentType: "application/json",
url: 'http://localhost:34468/Services/Service.svc/DoWork',
data: null,
cache: false,
processData: false,
error: function () {
alert('Error');
}
});
setTimeout("window.location.href = 'SecondPage.aspx';", 200);
Here I am not worried about the response of this service but it should update session variable after its completion as I have commented in the service implementation.
After calling this service I want to get it redirected to secondpage.aspx and the async service call should keep executing in the background.
But in the above case its waiting for complete execution of the service (i.e. executing synchronously) and then redirecting to the secondpage.aspx.
Let me know if there are any other ways to implement this.
You may just return a boolean value from your service. Before returning the boolean response, just start a new thread and do the background job.