参考文章:
启用 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
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/
其他参考