[英]Async call to WCF rest service with session variables access
我創建了WCF rest服務,然后使用ajax從javascript調用了該服務。 現在,我希望此服務異步執行,但它也應該可以訪問會話變量。
[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>
我從javascript消耗了此服務,如下所示,
$.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);
在這里,我不必擔心此服務的響應,但是正如我在服務實現中所評論的那樣,它應在會話變量完成后更新會話變量。
調用此服務后,我想將其重定向到secondpage.aspx,異步服務調用應繼續在后台執行。 但是在以上情況下,它等待服務的完全執行(即同步執行),然后重定向到secondpage.aspx。 讓我知道是否還有其他方法可以實現此目的。
您可能只是從服務中返回布爾值。 在返回布爾響應之前,只需啟動一個新線程並執行后台工作即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.