Json   发布时间:2019-10-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了不需要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

大佬总结

以上是大佬教程为你收集整理的不需要jsonp进行跨域的web-api (ssl enabled)全部内容,希望文章能够帮你解决不需要jsonp进行跨域的web-api (ssl enabled)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。