作为 Windows 服务托管的 c# WCF Restful Web 服务的跨源资源共享 [英] Cross Origin Resource Sharing for c# WCF Restful web service hosted as Windows service

查看:18
本文介绍了作为 Windows 服务托管的 c# WCF Restful Web 服务的跨源资源共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WCF Restful 服务,作为 Windows 服务托管.我想为我的服务添加跨域支持.但是,当我使用 global.asax 文件时,我可以轻松地做到这一点.但我想将我的服务作为 Windows 服务托管.

I have a WCF Restful service which I am hosting as Windows service. I want to add cross domain support to my service. However, i can do this easily when I use global.asax file. But I want to host my service as a windows service.

我创建了一个项目,将我的服务作为 Windows 服务托管.现在我面临的问题是,我现在无法添加跨域支持.我尝试了通过 app.config 文件找到的所有可能的解决方案,但没有一个有效.我在这些链接上尝试了解决方案:

i have created a project which host my service as windows service. Now the problem I am facing is, I am not able to add cross domain support now. I tried all possible solutions I could find through app.config file, but none works. I have tried solutions on these links:

dotnet 技巧

enable-cors.org

我尝试通过在每个服务合同方法中调用以下函数来设置代码中的标头.

I tried setting the header in the code using the following function by calling it in each service contract method.

private static void SetResponseHeader()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache, no-store");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Request-Methods", "GET, POST, PUT, DELETE, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
}

界面:

namespace ReaderService
{
[ServiceContract]
public interface INFCReader
{
    [OperationContract]
    [WebInvoke(UriTemplate = "GetLogin", Method = "POST")]
    GetLoginResults GetLogin(DisplayRequest dispRequest);
}

这里的 DisplayRequest 是一个类.

Here DisplayRequest is a class.

请大家帮忙.如果有人想查看任何其他代码,请告诉我.

Please help guys. Let me know if anybody want to have look at any other code.

非常感谢.

::::::

非常感谢托马斯的回复.我创建了一个类 MessageInspector,它实现了 IDispatchMessageInspector.我在 MessageInspector 类中有以下代码.

Thanks a lot Thomas for your reply. I created a class MessageInspector which implement IDispactchMessageInspector. I have following code in MessageInspector class.

public class MessageInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
        return null;
    }
}

我现在得到的错误是——未将对象引用设置为对象的实例."错误在上面代码的这一行

The error that I am getting now is -- 'Object reference not set to an instance of an object.' The error is at this line of the above code

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

我想要做的就是为我的 Web 服务添加 CORS 支持.请让我知道我是否做对了.或者有没有其他方法可以做到这一点.

All I want to do is add CORS support to my web service. Please let me know if I am doing it correctly. OR is there any other way to do the same.

推荐答案

我的疑问终于找到了解决方案.

Finally found a solution to my queries.

这里都有.支持跨源资源

很好的一步一步的解释.我想我自己永远无法弄清楚这一点.

Nice step by step explanation. I guess I could have never figured this out on my own.

代码:

创建2个类如下:

  1. MessageInspector 实现 IDispatchMessageInspector.
  2. BehaviorAttribute 实现了 AttributeIEndpointBehaviorIOOperationBehavior.
  1. MessageInspector implementing IDispatchMessageInspector.
  2. BehaviorAttribute implementing Attribute, IEndpointBehavior and IOperationBehavior.

包含以下详细信息:

//MessageInspector Class
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
namespace myCorsService
{
  public class MessageInspector  : IDispatchMessageInspector
  {
    private ServiceEndpoint _serviceEndpoint;

    public MessageInspector(ServiceEndpoint serviceEndpoint)
    {
      _serviceEndpoint = serviceEndpoint;
    }

    /// <summary>
    /// Called when an inbound message been received
    /// </summary>
    /// <param name="request">The request message.</param>
    /// <param name="channel">The incoming channel.</param>
    /// <param name="instanceContext">The current service instance.</param>
    /// <returns>
    /// The object used to correlate stateMsg. 
    /// This object is passed back in the method.
    /// </returns>
    public object AfterReceiveRequest(ref Message request, 
                                          IClientChannel channel, 
                                          InstanceContext instanceContext)
    {
      StateMessage stateMsg = null;
      HttpRequestMessageProperty requestProperty = null;
      if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
      {
        requestProperty = request.Properties[HttpRequestMessageProperty.Name]
                          as HttpRequestMessageProperty;
      }

      if (requestProperty != null)
      {
        var origin = requestProperty.Headers["Origin"];
        if (!string.IsNullOrEmpty(origin))
        {
          stateMsg = new StateMessage();
          // if a cors options request (preflight) is detected, 
          // we create our own reply message and don't invoke any 
          // operation at all.
          if (requestProperty.Method == "OPTIONS")
          {
            stateMsg.Message = Message.CreateMessage(request.Version, null);
          }
          request.Properties.Add("CrossOriginResourceSharingState", stateMsg);
        }
      }

      return stateMsg;
    }

    /// <summary>
    /// Called after the operation has returned but before the reply message
    /// is sent.
    /// </summary>
    /// <param name="reply">The reply message. This value is null if the 
    /// operation is one way.</param>
    /// <param name="correlationState">The correlation object returned from
    ///  the method.</param>
    public void BeforeSendReply(ref  Message reply, object correlationState)
    {
      var stateMsg = correlationState as StateMessage;

      if (stateMsg != null)
      {
        if (stateMsg.Message != null)
        {
          reply = stateMsg.Message;
        }

        HttpResponseMessageProperty responseProperty = null;

        if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
        {
          responseProperty = reply.Properties[HttpResponseMessageProperty.Name]
                             as HttpResponseMessageProperty;
        }

        if (responseProperty == null)
        {
          responseProperty = new HttpResponseMessageProperty();
          reply.Properties.Add(HttpResponseMessageProperty.Name,
                               responseProperty);
        }

        // Access-Control-Allow-Origin should be added for all cors responses
        responseProperty.Headers.Set("Access-Control-Allow-Origin", "*");

        if (stateMsg.Message != null)
        {
          // the following headers should only be added for OPTIONS requests
          responseProperty.Headers.Set("Access-Control-Allow-Methods",
                                       "POST, OPTIONS, GET");
          responseProperty.Headers.Set("Access-Control-Allow-Headers",
                    "Content-Type, Accept, Authorization, x-requested-with");
        }
      }
    }
  }

  class StateMessage
  {
    public Message Message;
  }
}

//BehaviorAttribute Class
using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace OpenBetRetail.NFCReaderService
{
  public class BehaviorAttribute : Attribute, IEndpointBehavior,
                                 IOperationBehavior
  {        
    public void Validate(ServiceEndpoint endpoint) { }

    public void AddBindingParameters(ServiceEndpoint endpoint,
                             BindingParameterCollection bindingParameters) { }

    /// <summary>
    /// This service modify or extend the service across an endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint that exposes the contract.</param>
    /// <param name="endpointDispatcher">The endpoint dispatcher to be
    /// modified or extended.</param>
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
                                      EndpointDispatcher endpointDispatcher)
    {
      // add inspector which detects cross origin requests
      endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
                                             new MessageInspector(endpoint));
    }

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

   public void Validate(OperationDescription operationDescription) { }

   public void ApplyDispatchBehavior(OperationDescription operationDescription,
                                     DispatchOperation dispatchOperation) { }

   public void ApplyClientBehavior(OperationDescription operationDescription,
                                   ClientOperation clientOperation) { }

   public void AddBindingParameters(OperationDescription operationDescription,
                             BindingParameterCollection bindingParameters) { }

  }
}

在此之后,您需要做的就是将此消息检查器添加到服务端点行为.

After this all you need to do is add this message inspector to service end point behavior.

ServiceHost host = new ServiceHost(typeof(myService), _baseAddress);
foreach (ServiceEndpoint EP in host.Description.Endpoints)
            EP.Behaviors.Add(new BehaviorAttribute());

谢谢大家的帮助.

这篇关于作为 Windows 服务托管的 c# WCF Restful Web 服务的跨源资源共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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