【发布时间】:2012-04-02 13:04:00
【问题描述】:
我创建了一个 WCF 休息服务,然后使用 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。 让我知道是否有其他方法可以实现这一点。
【问题讨论】:
标签: c# wcf jquery asynchronous asp.net-ajax