asp.net – 作为Windows服务托管的c#WCF Restful Web服务的跨源资源共享

前端之家收集整理的这篇文章主要介绍了asp.net – 作为Windows服务托管的c#WCF Restful Web服务的跨源资源共享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个WCF Restful服务,我作为 Windows服务托管.我想为我的服务添加跨域支持.但是,当我使用global.asax文件时,我可以轻松地做到这一点.但我想将我的服务作为Windows服务托管.

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

dotnet tricks

enable-cors.org

我尝试使用以下函数代码中设置标题,方法是在每个服务契约方法调用它.

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

接口:

  1. namespace ReaderService
  2. {
  3. [ServiceContract]
  4. public interface INFCReader
  5. {
  6. [OperationContract]
  7. [WebInvoke(UriTemplate = "GetLogin",Method = "POST")]
  8. GetLoginResults GetLogin(DisplayRequest dispRequest);
  9. }

这里DisplayRequest是一个类.

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

非常感谢.

编辑:::::::

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

  1. public class MessageInspector : IDispatchMessageInspector
  2. {
  3. public object AfterReceiveRequest(ref Message request,IClientChannel channel,InstanceContext instanceContext)
  4. {
  5. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
  6. if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
  7. {
  8. HttpContext.Current.Response.AddHeader("Cache-Control","no-cache");
  9. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",POST");
  10. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",Accept");
  11. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age","1728000");
  12. HttpContext.Current.Response.End();
  13. }
  14. return null;
  15. }
  16. }

我现在得到的错误是 – ‘对象引用没有设置为对象的实例.’
错误发生在上面代码的这一行

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

我想要做的就是为我的Web服务添加CORS支持.如果我做得对,请告诉我.或者还有其他方法可以做同样的事情.

解决方法

终于找到了我的查询解决方案.

一切都在这里. Supporting Cross Origin Resource

一步一步的解释很好.我想我可能从来没有想过这个问题.

码:

创建2个类,如下所示:

> MessageInspector实现IDispatchMessageInspector.
> BehaviorAttribute实现Attribute,IEndpointBehavior和IOperationBehavior.

具有以下细节:

  1. //MessageInspector Class
  2. using System;
  3. using System.ServiceModel;
  4. using System.ServiceModel.Channels;
  5. using System.ServiceModel.Dispatcher;
  6. using System.ServiceModel.Description;
  7. namespace myCoRSService
  8. {
  9. public class MessageInspector : IDispatchMessageInspector
  10. {
  11. private ServiceEndpoint _serviceEndpoint;
  12.  
  13. public MessageInspector(ServiceEndpoint serviceEndpoint)
  14. {
  15. _serviceEndpoint = serviceEndpoint;
  16. }
  17.  
  18. /// <summary>
  19. /// Called when an inbound message been received
  20. /// </summary>
  21. /// <param name="request">The request message.</param>
  22. /// <param name="channel">The incoming channel.</param>
  23. /// <param name="instanceContext">The current service instance.</param>
  24. /// <returns>
  25. /// The object used to correlate stateMsg.
  26. /// This object is passed back in the method.
  27. /// </returns>
  28. public object AfterReceiveRequest(ref Message request,InstanceContext instanceContext)
  29. {
  30. StateMessage stateMsg = null;
  31. HttpRequestMessageProperty requestProperty = null;
  32. if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
  33. {
  34. requestProperty = request.Properties[HttpRequestMessageProperty.Name]
  35. as HttpRequestMessageProperty;
  36. }
  37.  
  38. if (requestProperty != null)
  39. {
  40. var origin = requestProperty.Headers["Origin"];
  41. if (!string.IsNullOrEmpty(origin))
  42. {
  43. stateMsg = new StateMessage();
  44. // if a cors options request (preflight) is detected,// we create our own reply message and don't invoke any
  45. // operation at all.
  46. if (requestProperty.Method == "OPTIONS")
  47. {
  48. stateMsg.Message = Message.CreateMessage(request.Version,null);
  49. }
  50. request.Properties.Add("CrossOriginResourceSharingState",stateMsg);
  51. }
  52. }
  53.  
  54. return stateMsg;
  55. }
  56.  
  57. /// <summary>
  58. /// Called after the operation has returned but before the reply message
  59. /// is sent.
  60. /// </summary>
  61. /// <param name="reply">The reply message. This value is null if the
  62. /// operation is one way.</param>
  63. /// <param name="correlationState">The correlation object returned from
  64. /// the method.</param>
  65. public void BeforeSendReply(ref Message reply,object correlationState)
  66. {
  67. var stateMsg = correlationState as StateMessage;
  68.  
  69. if (stateMsg != null)
  70. {
  71. if (stateMsg.Message != null)
  72. {
  73. reply = stateMsg.Message;
  74. }
  75.  
  76. HttpResponseMessageProperty responseProperty = null;
  77.  
  78. if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
  79. {
  80. responseProperty = reply.Properties[HttpResponseMessageProperty.Name]
  81. as HttpResponseMessageProperty;
  82. }
  83.  
  84. if (responseProperty == null)
  85. {
  86. responseProperty = new HttpResponseMessageProperty();
  87. reply.Properties.Add(HttpResponseMessageProperty.Name,responseProperty);
  88. }
  89.  
  90. // Access-Control-Allow-Origin should be added for all cors responses
  91. responseProperty.Headers.Set("Access-Control-Allow-Origin","*");
  92.  
  93. if (stateMsg.Message != null)
  94. {
  95. // the following headers should only be added for OPTIONS requests
  96. responseProperty.Headers.Set("Access-Control-Allow-Methods","POST,OPTIONS,GET");
  97. responseProperty.Headers.Set("Access-Control-Allow-Headers",Accept,Authorization,x-requested-with");
  98. }
  99. }
  100. }
  101. }
  102.  
  103. class StateMessage
  104. {
  105. public Message Message;
  106. }
  107. }
  108.  
  109. //BehaviorAttribute Class
  110. using System;
  111. using System.ServiceModel.Channels;
  112. using System.ServiceModel.Description;
  113. using System.ServiceModel.Dispatcher;
  114.  
  115. namespace OpenBetRetail.NFCReaderService
  116. {
  117. public class BehaviorAttribute : Attribute,IEndpointBehavior,IOperationBehavior
  118. {
  119. public void Validate(ServiceEndpoint endpoint) { }
  120.  
  121. public void AddBindingParameters(ServiceEndpoint endpoint,BindingParameterCollection bindingParameters) { }
  122.  
  123. /// <summary>
  124. /// This service modify or extend the service across an endpoint.
  125. /// </summary>
  126. /// <param name="endpoint">The endpoint that exposes the contract.</param>
  127. /// <param name="endpointDispatcher">The endpoint dispatcher to be
  128. /// modified or extended.</param>
  129. public void ApplyDispatchBehavior(ServiceEndpoint endpoint,EndpointDispatcher endpointDispatcher)
  130. {
  131. // add inspector which detects cross origin requests
  132. endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
  133. new MessageInspector(endpoint));
  134. }
  135.  
  136. public void ApplyClientBehavior(ServiceEndpoint endpoint,ClientRuntime clientRuntime) { }
  137.  
  138. public void Validate(OperationDescription operationDescription) { }
  139.  
  140. public void ApplyDispatchBehavior(OperationDescription operationDescription,DispatchOperation dispatchOperation) { }
  141.  
  142. public void ApplyClientBehavior(OperationDescription operationDescription,ClientOperation clientOperation) { }
  143.  
  144. public void AddBindingParameters(OperationDescription operationDescription,BindingParameterCollection bindingParameters) { }
  145.  
  146. }
  147. }

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

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

谢谢大家帮助.

猜你在找的asp.Net相关文章