Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WCF全局(.asax)行为_Wcf_Rest_C# 4.0 - Fatal编程技术网

WCF全局(.asax)行为

WCF全局(.asax)行为,wcf,rest,c#-4.0,Wcf,Rest,C# 4.0,我想创建一个全局选项,当REST调用包含&format=json时,将响应作为json字符串输出 如果我在我的方法中输入以下字符串,它将起作用: WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; 但是,如果我在Global.asax文件的任何地方添加这一行,我会得到当前上下文的nullException: String format = ""; if (HttpContext.Curren

我想创建一个全局选项,当REST调用包含&format=json时,将响应作为json字符串输出

如果我在我的方法中输入以下字符串,它将起作用:

WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
但是,如果我在Global.asax文件的任何地方添加这一行,我会得到当前上下文的nullException:

String format = "";

if (HttpContext.Current.Request.QueryString["format"] != null)
  format = HttpContext.Current.Request.QueryString["format"];

if (String.Equals("json", format, StringComparison.OrdinalIgnoreCase))
  System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.Format = System.ServiceModel.Web.WebMessageFormat.Json;
异常在此处触发:

System.ServiceModel.Web.WebOperationContext.Current

有人知道我如何全局添加此功能(WCF)吗

您可以通过服务行为将自己的DispatchMessageInspector添加到WCF处理管道。就是如何做到这一点

要首先通过配置文件应用行为,您应该从BehaviorExtensionElement派生新类,并重写成员BehaviorType和CreateBehavior。 然后添加到类似的配置部分(使用您的完整类型名称)


<behaviors>
    <behavior configurationName="myServiceBehavior">
        <myBehavior />            
    </behavior>
</behaviors>


最后将此配置应用于您的服务。

我不必将其添加到Global.asax。我只需要它是全局的,这样它就会影响所有450个操作。我创建了这个,但它只是忽略了它的存在。有什么想法吗?也许行为与服务不相关。您可以展示您是如何做到这一点的,我想我将能够提供帮助。我认为问题在于将它添加到web.config中,我需要添加什么,这样它就不会忽略我了?解析器错误消息:配置中的元素无效。扩展“myBehavior”不是从正确的扩展基类型“System.ServiceModel.Configuration.BehaviorExtensionElement”派生的。请检查是否正确指定了扩展类型。“myBehavior”是扩展类的名称吗?
<behaviors>
    <behavior configurationName="myServiceBehavior">
        <myBehavior />            
    </behavior>
</behaviors>