安装包:Install-Package Microsoft.AspNet.WebApi.Cors
安装完成后,在配置文件后新增代码:
using System.Web.Http; namespace WebService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
在Controllers上引用:using System.Web.Http.Cors;
在对应的方法或者类做控制
using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace WebService.Controllers { [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")] public class TestController : ApiController { // Controller methods not shown... } }
在安装后编译出现问题:
错误 1 “TDServer.Areas.HelpPage.XmlDocumentationProvider”不实现接口成员“System.Web.Http.Description.IDocumentationProvider.GetResponseDocumentation(System.Web.Http.Controllers.HttpActionDescriptor)” c:UsersAdministratorDesktopTDServerTDServerAreasHelpPageXmlDocumentationProvider.cs 14 18 TDServer 错误 2 “TDServer.Areas.HelpPage.XmlDocumentationProvider”不实现接口成员“System.Web.Http.Description.IDocumentationProvider.GetDocumentation(System.Web.Http.Controllers.HttpControllerDescriptor)” c:UsersAdministratorDesktopTDServerTDServerAreasHelpPageXmlDocumentationProvider.cs 14 18 TDServer 警告 3 发现同一依赖程序集的不同版本间存在冲突。在 Visual Studio 中,请双击此警告(或选择此警告并按 Enter)以修复冲突;否则,请将以下绑定重定向添加到应用程序配置文件中的“runtime”节点: <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Net .Http.Formatting" culture="neutral" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-5.2.4.0 " newVersion="5.2.4.0 " /></dependentAssembly></assemblyBinding><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Http" culture="neutral" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-5.2.4.0 " newVersion="5.2.4.0 " /></dependentAssembly></assemblyBinding><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /><bindingRedirect oldVersion="0.0.0.0-6.0.0.0 " newVersion="6.0.0.0 " /></dependentAssembly></assemblyBinding> TDServer
安装包:Install-Package Microsoft.AspNet.WebApi -IncludePrerelease
安装后解决第三个问题。
安装包:install-package Microsoft.AspNet.WebApi.HelpPage