WCF + REST: Where is the request data?

前端 未结 5 1596
有刺的猬
有刺的猬 2020-12-01 11:23

I\'m currently developing a WCF RESTful service. Within the validation of the POST data, I am throwing exceptions if the request XML does not conform to our business rules.

5条回答
  •  执念已碎
    2020-12-01 12:08

    This unfortunately isn't supported- we had a similar need, and did it by calling internal members with reflection. We just use it in an error handler (so we can dump the raw request), but it works OK. I wouldn't recommend it for a system you don't own and operate though (eg, don't ship this code to a customer), since it can change at any time with a service pack or whatever.

    public static string GetRequestBody()
    {
        OperationContext oc = OperationContext.Current;
    
        if (oc == null)
            throw new Exception("No ambient OperationContext.");
    
        MessageEncoder encoder = oc.IncomingMessageProperties.Encoder;
        string contentType = encoder.ContentType;
        Match match = re.Match(contentType);
    
        if (!match.Success)
            throw new Exception("Failed to extract character set from request content type: " + contentType);
    
        string characterSet = match.Groups[1].Value;
    
        object bufferedMessage = operationContextType.InvokeMember("request",
            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField,
            null, oc, null);
    
        //TypeUtility.AssertType(bufferedMessageType, bufferedMessage);
    
        object messageData = bufferedMessageType.InvokeMember("MessageData",
            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty,
            null, bufferedMessage, null);
    
        //TypeUtility.AssertType(jsonBufferedMessageDataType, messageData);
    
        object buffer = jsonBufferedMessageDataType.InvokeMember("Buffer",
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty,
            null, messageData, null);
    
        ArraySegment arrayBuffer = (ArraySegment)buffer;
    
        Encoding encoding = Encoding.GetEncoding(characterSet);
    
        string requestMessage = encoding.GetString(arrayBuffer.Array, arrayBuffer.Offset, arrayBuffer.Count);
    
        return requestMessage;
    }
    

提交回复
热议问题