asp.net 跨域资源共享的C# WCF Restful Web服务托管为Windows服务

djp7away  于 2023-05-02  发布在  .NET
关注(0)|答案(3)|浏览(278)

我有一个WCF Restful服务,我作为Windows服务托管。我想在我的服务中添加跨域支持。但是,当我使用全局时,我可以很容易地做到这一点。asax文件。但是我想将我的服务托管为windows服务。
我已经创建了一个项目,它作为Windows服务托管我的服务。现在我面临的问题是,我现在不能添加跨域支持。我尝试了所有可能的解决方案,我可以通过应用程序找到。配置文件,但没有工作。我在这些链接上尝试了解决方案:
dotnet tricks
enable-cors.org
我尝试在每个服务契约方法中调用下面的函数来设置代码中的头。

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是一个类。
帮帮你们吧。让我知道如果有人想看看任何其他代码。
多谢了。
编辑:::::::
非常感谢托马斯的回复。我创建了一个实现IDispactchMessageInspector的MessageInspector类。我在MessageInspector类中有以下代码。

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;
    }
}

我现在得到的错误是-- '对象引用未设置为对象的示例。'错误在上面代码的这一行

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

我所要做的就是将CORS支持添加到我的Web服务中。请让我知道我做得是否正确。或者有其他方法可以做同样的事情。

bkhjykvo

bkhjykvo1#

终于找到了解决我的疑问。
都在这里。Supporting Cross Origin Resource
一步一步的解释。我想我一个人永远也搞不清楚。

验证码:

创建2个类,如下所示:

  1. MessageInspector实现IDispatchMessageInspector
  2. BehaviorAttribute实现AttributeIEndpointBehaviorIOperationBehavior
    包含以下详细信息:
//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) { }

  }
}

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

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

谢谢你们的帮助。

xqnpmsa8

xqnpmsa82#

我认为在WCF世界中最接近Application_BeginRequest的是Message Inspectors
消息检查器是一个可扩展性对象,可以编程地或通过配置在服务模型的客户端运行时和调度运行时中使用,并且可以在接收消息之后或发送消息之前检查和更改消息。
要使用自定义消息检查器,您必须:
1.创建实现IDispatchMessageInspector接口的类(自定义检查器)
1.将自定义检查器添加到您服务的DispatchRuntime。MessageInspectors集合
Here你可以找到更多的信息和一些示例代码如何做到这一点。

oaxa6hgo

oaxa6hgo3#

如果没有你的答案,我永远不会这样做后,花了一天的时间来弄清楚,我尝试了这2类,但直接在应用程序中使用它们。配置但从未工作

相关问题