不需要jsonp进行跨域的web-api (ssl enabled)

参考文章

启用 ASP.NET Web API 中的跨起源请求(Enabling Cross-Origin Requests in ASP.NET Web API)

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

关键在于给web-api工程添加nuget包,命令如下:

Install-Package Microsoft.AspNet.WebApi.Cors -pre -project web-api-project

然后以如下方式在web-api的配置上允许的网站来源:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com","*","*");
        config.EnableCors(cors);
        // ...
    }
}

如此,可以使用json调用此web-api,并保证web-api的输出为对象类型。

不过,以此(可能)会出现的问题:

1. 编译无误,运行异常

Could not load file or assembly 'System.Web.Http,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest deFinition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

是因为不同dll需要使用的此dll的版本不同,我们就告诉project统统使用目前引入的5.0版本,在web.config添加如下配置(连同System.Net.Http.Formatting一起,否则即便运行网站不出错,运行到那也会出错):

      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

引用:

Could not load file or assembly System.Net.Http,Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

http://stackoverflow.com/questions/18982682/could-not-load-file-or-assembly-system-net-http-version-4-0-0-0-with-asp-net-m

2. 运行时读取GlobalConfiguration.Configuration异常

[FieldAccessException: Attempt by method 'System.Web.Http.GlobalConfiguration..cctor()' to access field 'System.Web.Http.GlobalConfiguration.CS$<>9__CachedAnonymousMethodDelegate2' Failed.]
System.Web.Http.GlobalConfiguration..cctor() +48

[TypeInitializationException: The type initializer for 'System.Web.Http.GlobalConfiguration' threw an exception.]
System.Web.Http.GlobalConfiguration.get_Configuration() +0
BalkanButton.Global.Application_Start(Object sender,EventArgs e) in 

解决

Install-Package Microsoft.AspNet.WebApi -IncludePrerelease


引用:

WebAPI and CORS enabled REST services

http://wp.sjkp.dk/webapi-and-cors-enabled-rest-services/

其他参考

WebAPI OData 5.0 Beta - Accessing GlobalConfiguration throws Security Error

WebAPI CORS and Ninject

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...