2012-04-02 68 views
0

我創建了一個WCF rest服務,然後使用ajax從javascript調用該服務。現在我希望這個服務是異步執行的,但它也應該可以訪問會話變量。使用會話變量訪問WCF rest服務的異步調用訪問

[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。 讓我知道是否有其他方法來實現這一點。

回答

0

您可能僅從您的服務返回一個布爾值。在返回布爾響應之前,只需啓動一個新線程並執行後臺任務。

+0

這裏有一個重要的注意事項 - 如果您的服務託管在iis上,請不要**啓動新的線程。除非最近這種行爲發生了變化,否則iis線程中未捕獲的異常會導致w3wp.exe進程關閉,從而導致整個網站崩潰。 如果你想做任何後臺工作,我建議您將WCF服務作爲Windows服務 – 2012-04-02 13:34:11

+0

好吧..謝謝。 – 2012-04-02 13:51:47