我想创建一个全局选项,当 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 处理管道。 Here是如何做到这一点。
要首先通过配置文件应用行为,您应该从BehaviorExtensionElement派生新类并覆盖成员BehaviorType和CreateBehavior。 然后添加到与此类似的配置部分(使用您的完整类型名称)
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="myBehavior" type="SomeNamespace.MyBehaviorExtensionElement, AssemblyName,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
还有那个
<behaviors>
<behavior configurationName="myServiceBehavior">
<myBehavior />
</behavior>
</behaviors>
最后将此配置应用到您的服务。
关于WCF 全局 (.asax) 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2903636/