将application / x-www-form-urlencoded发布到SOAP / JSON WCF服务

时间:2014-05-07 18:16:24

标签: c# json web-services wcf iclientmessageinspector

背景

前一段时间我写了一个WCF服务,它大量使用自定义操作调用程序,错误处理程序和行为 - 其中许多严重依赖于某种类型的输入消息,或者消息的基本消息类型(每个DataContract)继承自基类和许多接口)。还为所涉及的各种接口和类设置了许多单元和集成测试。此外,每次修改软件时都必须经过严格的签核过程,重写服务层并不是我的乐趣。

它目前已配置为允许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}

还要考虑服务控制如下:

[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(根据以下链接)。

我发现了很多帖子,建议如何使用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

虽然我没有发现任何特别有用的东西。

问题

有没有什么方法可以在消息到达操作合同之前拦截它,并将它从客户端的输入转换为我的自定义类,然后让应用程序的其余部分按照正常情况对其进行处理?

自定义消息检查器?操作选择器?自从我进入WCF的内心已经有一段时间了,所以我现在有点生疏了。我花了一段时间寻找下面的图像,因为我记得使用它来提醒我调用堆栈 - 如果它仍然相关!

http://i.stack.imgur.com/pT4o0.gif

2 个答案:

答案 0 :(得分:3)

所以,我使用消息检查器解决了这个问题。它不漂亮,但它适用于我的情况!

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属性不存在,则将属性名称反序列化)。

答案 1 :(得分:2)

不确定您有多自由更新ServiceContract,但我会尝试将其扩展如下:

[ServiceContract(Namespace = "https://my.custom.domain.com/")]
public interface IMyContract {
    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "process")]
    MyCustomResponse Process(MyCustomRequest req);

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "processForm")]
    MyCustomResponse ProcessForm(MyCustomRequest req);
}

然后会给这个客户端新的URL发布到。