惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Register - Security
The Register - Security
云风的 BLOG
云风的 BLOG
U
Unit 42
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
D
Docker
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
Secure Thoughts
Hacker News: Ask HN
Hacker News: Ask HN
Vercel News
Vercel News
S
Security @ Cisco Blogs
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
I
Intezer
MongoDB | Blog
MongoDB | Blog
AI
AI
MyScale Blog
MyScale Blog
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
W
WeLiveSecurity
博客园 - 叶小钗
S
SegmentFault 最新的问题
N
News | PayPal Newsroom
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
DataBreaches.Net
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
H
Help Net Security
美团技术团队
博客园 - 司徒正美
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Vulnerabilities – Threatpost
TaoSecurity Blog
TaoSecurity Blog
N
Netflix TechBlog - Medium
L
Lohrmann on Cybersecurity
J
Java Code Geeks
量子位
Martin Fowler
Martin Fowler
博客园_首页

博客园 - 为森

NPM设置镜像 关于nodejs4.0 npm乱码以及离线全局安装时要注意的问题 C# 正则表达式 转自-每日一bo 关于async & await(TAP)异步模型的异常捕获 一个Public的字段引起的,谈谈继承中的new 解决Bootstrap 附加导航(Affix)的问题和使用时若干注意事项 一次小异常的排查,悲剧的无以复加!!! async & await 小扩展大用处,自己扩展一个ForeachRead吧 转 常用工具和技术 implicit和 explicit关键字 MVC 自定义 以表达式树为参数的htmlhelper 解决解密时出现"要解密的数据的长度无效" 或 "填充无效无法被移除" 的错误 EF 的一些不常用的功能 详细说明 配置 Sublime Text 开发node.js(windows)包括sub2和sub3的区别 sql 判断 数据库 表 字段 是否存在 转 WCF中同步和异步通讯总结 关于WCF 解决EF一对一或多对一的删除
WCF 自托管、无配置文件实现jsonp(跨域)的访问
为森 · 2015-11-25 · via 博客园 - 为森

以下内容基于WCF4.0,本文将对比讨论配置文件方案和无配置文件方案的实现方式。

    WCF4.0加入了对RESTFU和标准终结点的支持,这为实现跨域提供了简单的方式。

一、有配置文件的情况:

首先我们先定义一个服务:

[ServiceContract]
public class MinitorServer
{
        [OperationContract]
        public bool Test()
        {
            return true;
        }
}

    在这里我故意没有声明接口,顺便废话几句,正常情况下我们应该定义接口去显示服务契约(servercontract)和操作契约(operationcontract),但是对于一些简单的服务,我们可以省略接口的定义,做事不应循规蹈矩。

1、配置文件

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
   <system.serviceModel>
     <behaviors>
      <endpointBehaviors>
         <behavior name="webHttp">
              <webHttp automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" />
          </behavior>
         </endpointBehaviors>
          </behaviors>
     <standardEndpoints>
       <webHttpEndpoint>
         <standardEndpoint crossDomainScriptAccessEnabled="true" />
       </webHttpEndpoint>
     </standardEndpoints>
     <bindings>
       <webHttpBinding>
         <binding crossDomainScriptAccessEnabled="true"  />
       </webHttpBinding>
     </bindings>
     <services>      
       <service name="HD.ExamMonitorClient.MinitorServer">
         <endpoint kind="webHttpEndpoint"
                   behaviorConfiguration="webHttp"
                   address="http://localhost:8088/MonitorServer/"
                   contract="HD.ExamMonitorClient.MinitorServer"/>
       </service>
     </services>
   </system.serviceModel>
 </configuration>

在这里比较重要的是:

    kind="webHttpEndpoint" 表示该终结点采用标准终结点;

  crossDomainScriptAccessEnabled="true" 设置该终结点可以响应跨域请求;

  automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" 自动将响应类型设置为json,当然你可以根据自己的需求修改为xml。

2、修改服务加入attribute用来响应get请求:

[ServiceContract]
public class MinitorServer
{
        [OperationContract]
        [WebGet]
        public bool Test()
        {
            return true;
        }
}

在这里如果你上一步没有配置automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"那你应该将[WebGet] 改为[WebGet(ResponseFormat=WebMessageFormat.Json)],必须要注意的是:如果单纯响应非跨域请求,不需要设置defaultOutgoingResponseFormat="Json" ,因为在http请求的头部已经指定了数据类型。

3、在控制台中托管服务:

using(host = new ServiceHost(typeof(MinitorServer)))
{
    host.Open();
   Console.ReadKey(); }

4、浏览器测试

$(function () {
             $.ajax({
                 type: "get",
                 url: "http://localhost:8088/MonitorServer/Test",
                 dataType: "jsonp",
                 success: function (ret) {
                     console.log(ret);
                 }
             });
         });

二、无配置文件方式:

无配置文件方式的难点在于不能直接设置标准终结点。在这里要指出,标准终结点=绑定+终结点行为,所以我们可以这样设置:

using(host = new ServiceHost(typeof(MinitorServer)))
{

            //定义一个webHttp的绑定
            WebHttpBinding webBing = new WebHttpBinding();
            webBing.CrossDomainScriptAccessEnabled = true;
            
            //定义一个终结点行为
            var endpointBehavior =new WebHttpBehavior();
            endpointBehavior.AutomaticFormatSelectionEnabled = true;
            endpointBehavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json;

            
            //加入服务
            var end = host.AddServiceEndpoint(typeof(MinitorServer), webBing, "http://localhost:8088/MonitorServer/");
            end.Behaviors.Add(endpointBehavior);
            
           

            host.Open();
            Console.ReadKey();  
}            

现在可以将配置文件删除了。

另外如果讨厌去为每个操作协定设置[WebGet],那么这里有个简单方式,在open之前,我们循环为每个操作协定加入行为即可。

var operationBehavio=new WebGetAttribute();
foreach (var item in end.Contract.Operations)
{
                if (item.Behaviors.Find<WebGetAttribute>() == null)
                {
                    item.Behaviors.Add(operationBehavio);
                }
 }