背景
我不久前编写了一个 WCF 服务,它大量使用自定义操作调用程序、错误处理程序和行为 - 其中许多严重依赖于特定类型的输入消息,或消息的基本消息类型(每个 DataContract继承自一个基类和一些接口(interface))。还为涉及的各种接口(interface)和类设置了许多单元和集成测试。此外,软件每次修改都要经过一个轰轰烈烈的签核过程,重写服务层也不是我的乐趣所在。
当前配置为允许 JSON 和 SOAP 请求进入。
问题
由于旧软件的限制,客户希望使用 application/x-www-form-urlencoded 内容类型 POST 到此服务。通常,该服务会接受如下所示的 JSON 请求:
{
"username":"jeff",
"password":"mypassword",
"myvalue":12345
}
而客户端可以发送的application/x-www-form-urlencoded消息体看起来有点像这样:
username=jeff&password=mypassword&myvalue=12345
或者,客户通知我他们可以按如下方式格式化消息(如果有用的话):
myjson={username:jeff,password:mypassword,myvalue:12345}
还要考虑服务契约(Contract)如下所示:
[ServiceContract(Namespace = "https://my.custom.domain.com/")]
public interface IMyContract {
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "process")]
MyCustomResponse Process(MyCustomRequest req);
}
我想保留 MyCustomRequest,并避免将其替换为 Stream(按照以下链接)。
我发现许多帖子都建议如何使用流 OperationContract 参数实现此目的,但在我的特定实例中,更改 OperationContract 参数的类型需要大量工作。下面的帖子详细介绍了一些内容:
Using x-www-form-urlencoded Content-Type in WCF
Best way to support "application/x-www-form-urlencoded" post data with WCF?
http://www.codeproject.com/Articles/275279/Developing-WCF-Restful-Services-with-GET-and-POST
虽然我还没有发现其中任何一个特别有用。
问题
有什么方法可以在消息到达操作契约之前拦截消息,并将其从客户端输入转换为我的自定义类,然后让应用程序的其余部分正常处理它?</p>
自定义消息检查器?操作选择器?自从我深入了解 WCF 以来已经有一段时间了,所以我现在有点生疏了。我花了一段时间寻找下图,因为我记得用它来提醒我调用堆栈 - 如果它仍然相关的话!
最佳答案
因此,我使用消息检查器解决了这个问题。它不是很漂亮,但它适用于我的情况!
using System;
public class StreamMessageInspector : IDispatchMessageInspector {
#region Implementation of IDispatchMessageInspector
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) {
if (request.IsEmpty) {
return null;
}
const string action = "<FullNameOfOperation>";
// Only process action requests for now
var operationName = request.Properties["HttpOperationName"] as string;
if (operationName != action) {
return null;
}
// Check that the content type of the request is set to a form post, otherwise do no more processing
var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
var contentType = prop.Headers["Content-Type"];
if (contentType != "application/x-www-form-urlencoded") {
return null;
}
///////////////////////////////////////
// Build the body from the form values
string body;
// Retrieve the base64 encrypted message body
using (var ms = new MemoryStream()) {
using (var xw = XmlWriter.Create(ms)) {
request.WriteBody(xw);
xw.Flush();
body = Encoding.UTF8.GetString(ms.ToArray());
}
}
// Trim any characters at the beginning of the string, if they're not a <
body = TrimExtended(body);
// Grab base64 binary data from <Binary> XML node
var doc = XDocument.Parse(body);
if (doc.Root == null) {
// Unable to parse body
return null;
}
var node = doc.Root.Elements("Binary").FirstOrDefault();
if (node == null) {
// No "Binary" element
return null;
}
// Decrypt the XML element value into a string
var bodyBytes = Convert.FromBase64String(node.Value);
var bodyDecoded = Encoding.UTF8.GetString(bodyBytes);
// Deserialize the form request into the correct data contract
var qss = new QueryStringSerializer();
var newContract = qss.Deserialize<MyServiceContract>(bodyDecoded);
// Form the new message and set it
var newMessage = Message.CreateMessage(OperationContext.Current.IncomingMessageVersion, action, newContract);
request = newMessage;
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState) {
}
#endregion
/// <summary>
/// Trims any random characters from the start of the string. I would say this is a BOM, but it doesn't seem to be.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private string TrimExtended(string s) {
while (true) {
if (s.StartsWith("<")) {
// Nothing to do, return the string
return s;
}
// Replace the first character of the string
s = s.Substring(1);
if (!s.StartsWith("<")) {
continue;
}
return s;
}
}
}
然后我创建了一个端点行为并通过 WCF 配置添加了它:
public class StreamMessageInspectorEndpointBehavior : BehaviorExtensionElement, IEndpointBehavior {
public void Validate(ServiceEndpoint endpoint) {
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) {
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) {
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new StreamMessageInspector());
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) {
}
#region Overrides of BehaviorExtensionElement
protected override object CreateBehavior() {
return this;
}
public override Type BehaviorType {
get { return GetType(); }
}
#endregion
}
以下是配置更改的摘录:
<extensions>
<behaviorExtensions>
<add name="streamInspector" type="My.Namespace.WCF.Extensions.Behaviors.StreamMessageInspectorEndpointBehavior, My.Namespace.WCF, Version=1.0.0.0, Culture=neutral" />
</behaviorExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="MyEndpointBehavior">
<streamInspector/>
</behavior>
</endpointBehaviors>
QueryStringSerializer.Deserialize() 将查询字符串反序列化为 DataContract(基于 DataMember.Name 属性,如果 DataMember 属性不存在,则为属性名称)。
关于c# - 将 application/x-www-form-urlencoded 发布到 SOAP/JSON WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23525261/