• 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格式。

  • 相关阅读:
    EntityFramework6.X 之Relationship
    EntityFramework6.X 之Inheritance Stategy
    EntityFramework6.X 之 Fulent
    EntityFramework6.X之DataAnnotations
    EntityFramework6.X 之 Database Initialization
    EntityFramework6.X 之DbContex
    EntityFramework6.X 之LocalDB&ConnectionString
    EntityFramework6.X之概述
    C提高_day03_玩转多级指针
    C提高_day03_二级指针内存示意图(没有比这重要的了)
  • 原文地址:https://www.cnblogs.com/mickeyooo/p/wcf_4_rest_services_jsonp.html
Copyright © 2020-2023  润新知