我有2个长期运行的服务方法,我想限制在白天的某个时间段。主要是营业时间以外。这些服务方法是较大合同的一部分,其中包含我希望在所有时间内可用的方法。在不改变整体合同的情况下限制2种方法的最佳方法是什么。 Application_BeginRequest会成为开始的地方吗?返回503服务不适合这里吗?如何检测所请求的方法?
答案 0 :(得分:0)
您不需要使用只能MessageInspector in WCF使用的开始请求 并尝试拦截所有操作并使用您想要的状态代码进行响应 您需要的只是按照以下步骤操作
<强> 1步骤强>
在您的代码中,您应该添加MessageInspectorExtension
class MessageInspectorExtension : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof(MessageInspector); }
}
protected override object CreateBehavior()
{
return new MessageInspector();
}
}
MessageInspector
将完成您需要的所有工作,并且应该像这样定义
//here the `MessageInspector` class showing what are the interfaces responsable for doing this
public class MessageInspector : IDispatchMessageInspector, IServiceBehavior, IEndpointBehavior
{
}
您需要的主要方法是
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
//here you can add your logic to check hour and time
//
return null;
}
Which is called after an inbound message has been received but before the message is dispatched to the intended operation
和
public void BeforeSendReply(ref message reply,object correlationState)
{
if(!reply.IsFault)返回;
if (!reply.Headers.Action.StartsWith("your actin here", StringComparison.Ordinal)) return;
//get the string value for desired response code
string statusCodeString = reply.Headers.Action.Substring(17);
//convert to int
int statusCodeInt;
if (!int.TryParse(statusCodeString, out statusCodeInt)) return;
//cast to HttpStatusCode
System.Net.HttpStatusCode statusCode = System.Net.HttpStatusCode.ServiceUnavailable;
try
{
statusCode = (System.Net.HttpStatusCode)statusCodeInt;
}
catch (Exception ex)
{
return;
}
// Here the response code is changed
reply.Properties[HttpResponseMessageProperty.Name] = new HttpResponseMessageProperty() { StatusCode = statusCode };
}
}
}
在操作返回之后但在发送回复消息之前调用该函数
<强>两步强>
在您的应用配置中,您必须添加如下所示的行为定义
<behaviors>
<endpointBehaviors>
<behavior name="ServiceBehaviorWithInterceptor">
<ServiceInspector/>
</behavior>
</endpointBehaviors>
<behaviors>
<!--Extensions-->
<extensions>
<behaviorExtensions>
<add name="ServiceInspector" type="yourNameSpace.MessageInspector.MessageInspectorExtension, assemblyname, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
&#34; 3步
<service name="yourServiceContractFullName" behaviorConfiguration="ServiceBehaviorWithInterceptor">
<host>
<baseAddresses>
<add baseAddress="http://yourserver:port/root/yourServiceContract" />
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpsBindingConfig" contract="YourContract" />
</service>