我正在尝试在 asp.net web api 中设置 CORS。我的 WebApiConfig.cs 是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Cors;
using System.Web.Http.Routing;
namespace WebApplication2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
var cors = new EnableCorsAttribute("http://localhost", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "bootstrap",
routeTemplate: "abp/{controller}"
);
}
}
}
我还在我的 Controller 中添加了 header ,即:
namespace WebApplication2.Controllers
{
public class BootStrapController : ApiController
{
public void Options(string locale, string deviceType)
{
string origin = HttpContext.Current.Request.Headers.Get("Origin") ?? "";
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", origin);
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", HttpContext.Current.Request.Headers["Access-Control-Request-Methods"]);
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", HttpContext.Current.Request.Headers["Access-Control-Request-Headers"]);
HttpContext.Current.Response.End();
}
public object Get(string locale, string deviceType)
{
string origin = HttpContext.Current.Request.Headers.Get("Origin") ?? "";
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
然而,我在服务器响应中没有任何访问控制或任何附加 header 。如果您需要更多信息,请告诉我。
最佳答案
请访问http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api .您将获得在 WebAPI 中实现 CORS 的完整指南。
更新: 要在 WEBAPI 中实现 CORS,请按照以下步骤操作:
在您的解决方案中添加 CORS NuGet 包。在 Visual Studio 中,从工具菜单中选择库包管理器,然后选择包管理器控制台。在包管理器控制台窗口中,键入以下命令:
安装包Microsoft.AspNet.WebApi.Cors打开文件 App_Start/WebApiConfig.cs。将以下代码添加到 WebApiConfig.Register 方法。
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); } }
接下来,将 [EnableCors] 属性添加到 BootStrapController 类:
[EnableCors(origins: "*", headers: "*", methods: "*")] public class BootStrapController : ApiController { // Controller methods }
来源、标题和方法可能会根据您的需要而有所不同。
关于c# - CORS 和 ASP.Net Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37685446/