使用WCF REST Service POST方法处理Json请求数据 [英] Handle Json Request data in WCF REST Service POST method

查看:444
本文介绍了使用WCF REST Service POST方法处理Json请求数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用POST方法和OBJECT作为输入参数来创建REST服务.而客户端请求无法获取客户端已发布的实际JSON数据.有什么方法可以从C#WCF服务中提取JSON代码.

我的代码:

namespace ACTService
{
  public class AssortmentService : IAssortmentService
  {
    public void DeleteColor(DeleteColorContarct objdelcolor)
    {
         new Methods.ColorUI().DeleteColorDetails(objdelcolor);
    }
  }
}

,我的界面为

namespace ACTService
{
  [ServiceContract]
  public interface IAssortmentService
  {
    [OperationContract]
    [WebInvoke(UriTemplate = "DeleteColor", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Wrapped)]
    void DeleteColor(DeleteColorContarct objColor);
  }
}

我需要访问其他类文件 ColorUI

中的JSON格式

解决方案

WCF提供了许多可扩展的点,其中之一就是称为MessageInspector的功能.您可以创建一个自定义消息检查器,以在将请求反序列化为C#对象之前接收该请求.并使用Raw请求数据尽您所能.

要实现它,您需要实现如下的System.ServiceModel.Dispatcher.IDispatchMessageInspector接口:

public class IncomingMessageLogger : IDispatchMessageInspector
{
    const string MessageLogFolder = @"c:\temp\";
    static int messageLogFileIndex = 0;

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        string messageFileName = string.Format("{0}Log{1:000}_Incoming.txt", MessageLogFolder, Interlocked.Increment(ref messageLogFileIndex));
        Uri requestUri = request.Headers.To;

        HttpRequestMessageProperty httpReq = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

        // Decode the message from request and do whatever you want to do.
        string jsonMessage = this.MessageToString(ref request);

        return requestUri;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
    }
}

这是完整的代码段摘要. 实际来源.

现在,您需要将此消息检查器添加到端点行为.为此,您将实现如下所示的System.ServiceModel.Description.IEndpointBehavior接口:

public class InsepctMessageBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new IncomingMessageLogger());
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

现在,如果您正在自托管,即以编程方式托管服务,则可以将此新实现的行为直接附加到服务端点.例如

endpoint.Behaviors.Add(new IncomingMessageLogger());

但是,如果您已经在IIS中托管了WCF Rest服务,那么您将通过配置注入新的Behavior.为了实现这一点,您必须创建一个从BehaviorExtensionElement派生的附加类:

public class InspectMessageBehaviorExtension : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(InsepctMessageBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new InsepctMessageBehavior();
    }
}

现在,在您的配置中,首先在system.servicemodel标签下注册行为:

    <extensions>
      <behaviorExtensions>
        <add name="inspectMessageBehavior" 
type="WcfRestAuthentication.MessageInspector.InspectMessageBehaviorExtension, WcfRestAuthentication"/>
      </behaviorExtensions>
    </extensions>

现在将此行为添加到端点"行为中:

  <endpointBehaviors>
    <behavior name="defaultWebHttpBehavior">
      <inspectMessageBehavior/>
      <webHttp defaultOutgoingResponseFormat="Json"/>
    </behavior>
 </endpointBehaviors>

在端点中设置属性behaviorConfiguration="defaultWebHttpBehavior".

就是这样,您的服务现在将在反序列化它们之前捕获所有消息.

i am creating the REST service with POST method and OBJECT as input param. while client request am unable to get the actual JSON data client have posted. Is there any way to dig the JSON code from the C# WCF service.

My code:

namespace ACTService
{
  public class AssortmentService : IAssortmentService
  {
    public void DeleteColor(DeleteColorContarct objdelcolor)
    {
         new Methods.ColorUI().DeleteColorDetails(objdelcolor);
    }
  }
}

and my interface as

namespace ACTService
{
  [ServiceContract]
  public interface IAssortmentService
  {
    [OperationContract]
    [WebInvoke(UriTemplate = "DeleteColor", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Wrapped)]
    void DeleteColor(DeleteColorContarct objColor);
  }
}

I need to access the JSON format in other class file ColorUI

解决方案

WCF provides a lot of extensible points one of them is a feature called MessageInspector. You can create a custom message inspector to receive the request before it get de-serialized to C# object. And do what ever you can with Raw request data.

In order to implement it you would need to implement System.ServiceModel.Dispatcher.IDispatchMessageInspector interface like below:

public class IncomingMessageLogger : IDispatchMessageInspector
{
    const string MessageLogFolder = @"c:\temp\";
    static int messageLogFileIndex = 0;

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        string messageFileName = string.Format("{0}Log{1:000}_Incoming.txt", MessageLogFolder, Interlocked.Increment(ref messageLogFileIndex));
        Uri requestUri = request.Headers.To;

        HttpRequestMessageProperty httpReq = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

        // Decode the message from request and do whatever you want to do.
        string jsonMessage = this.MessageToString(ref request);

        return requestUri;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
    }
}

Here's the complete code snippet gist. Actual source.

Now you need to add this Message inspector to end point behavior. To achieve that you would be implementing System.ServiceModel.Description.IEndpointBehavior interface like below:

public class InsepctMessageBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new IncomingMessageLogger());
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

Now if you are on selfhosting i.e. you are hosting your service programmatically you can directly attach this newly implemented behavior to your service end point. E.g.

endpoint.Behaviors.Add(new IncomingMessageLogger());

But If you have hosted the WCF Rest service in IIS then you would be injecting the new Behavior via configuration. In order to achieve that you have to create an additional class derived from BehaviorExtensionElement:

public class InspectMessageBehaviorExtension : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(InsepctMessageBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new InsepctMessageBehavior();
    }
}

Now in your configuration first register the behavior under system.servicemodel tag:

    <extensions>
      <behaviorExtensions>
        <add name="inspectMessageBehavior" 
type="WcfRestAuthentication.MessageInspector.InspectMessageBehaviorExtension, WcfRestAuthentication"/>
      </behaviorExtensions>
    </extensions>

Now add this behavior to the Endpoint behavior:

  <endpointBehaviors>
    <behavior name="defaultWebHttpBehavior">
      <inspectMessageBehavior/>
      <webHttp defaultOutgoingResponseFormat="Json"/>
    </behavior>
 </endpointBehaviors>

set the attribute behaviorConfiguration="defaultWebHttpBehavior" in your endpoint.

That's it your service will now capture all the messages before deserializing them.

这篇关于使用WCF REST Service POST方法处理Json请求数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆