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。 让我知道是否有其他方法来实现这一点。
这里有一个重要的注意事项 - 如果您的服务托管在iis上,请不要**启动新的线程。除非最近这种行为发生了变化,否则iis线程中未捕获的异常会导致w3wp.exe进程关闭,从而导致整个网站崩溃。 如果你想做任何后台工作,我建议您将WCF服务作为Windows服务 – 2012-04-02 13:34:11
好吧..谢谢。 – 2012-04-02 13:51:47