• WCF 4.0 REST Service JSON跨域调用


     最近在项目中用到了 WCF4.0 REST。在跨域调用时走了不少弯路,查了不少技术强人的文章,其实它真的就这么容易。好了不废话了直接贴代码。

     调用的服务类:

     1     [ServiceContract]
     2     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     3     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
     4     [JavascriptCallbackBehavior(UrlParameterName="callback")]
     5     public class Writing
     6     {
     7 
     8         [WebGet(UriTemplate="", ResponseFormat=WebMessageFormat.Json)]
     9         public List<Top> GetCollection()
    10         {
    11             WritingContext _context = new WritingContext();
    12 
    13             return _context.Database
    14                 .SqlQuery<Top>("SELECT TOP 15 WRITINGID Id, WRITING Title FROM YC_WRITING ORDER BY WRITINGID DESC")
    15                 .ToList();
    16         }
    17     }
      配置文件:
     1   <system.serviceModel>
     2     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
     3     <standardEndpoints>
     4       <webHttpEndpoint>
     5         <!-- 
     6             Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
     7             via the attributes on the <standardEndpoint> element below
     8         -->
     9         <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" 
    10                           crossDomainScriptAccessEnabled="true"/>
    11       </webHttpEndpoint>
    12     </standardEndpoints>
    13   </system.serviceModel>

    真正实现夸域调用只需要两步:

    1. 类文件中添加[JavascriptCallbackBehavior(UrlParameterName="callback")]
    2. 配置文件的 standardEndpoint 添加 crossDomainScriptAccessEnabled="true"

    最后需要注意的是WCF REST service 模板生成的配置文件automaticFormatSelectionEnabled属性默认是true,需要将其设置为false否则firefox里返回的将是xml格式。

  • 相关阅读:
    两步验证杀手锏:Java 接入 Google 身份验证器实战
    涨姿势:Spring Boot 2.x 启动全过程源码分析
    Spring Cloud 升级最新 Finchley 版本,踩了所有的坑!
    Spring Boot 2.x 启动全过程源码分析(上)入口类剖析
    推荐:7 月份值得一看的 Java 技术干货!
    屌炸天,Oracle 发布了一个全栈虚拟机 GraalVM,支持 Python!
    Spring Boot 核心配置文件 bootstrap & application 详解。
    出场率比较高的一道多线程安全面试题
    凉凉了,Eureka 2.x 停止维护,Spring Cloud 何去何从?
    读写Excel
  • 原文地址:https://www.cnblogs.com/mickeyooo/p/wcf_4_rest_services_jsonp.html
Copyright © 2020-2023  润新知