对具有会话变量访问权限的WCF rest服务的异步调用

本文关键字:WCF rest 服务 调用 异步 权限 访问权 会话 变量 访问 | 更新日期: 2023-09-27 18:29:48

我创建了一个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。请告诉我是否还有其他方法可以实现这一点。

对具有会话变量访问权限的WCF rest服务的异步调用

您可以从服务中返回一个布尔值。在返回布尔响应之前,只需启动一个新线程并完成后台工作。