C# CORS与ASP.NETWebAPI
我正在尝试在asp.net web api中设置CORS。我的WebApiConfig.cs是:C# CORS与ASP.NETWebAPI,c#,asp.net-web-api,cors,C#,Asp.net Web Api,Cors,我正在尝试在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 WebApp
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}"
);
}
}
}
我的控制器中还附加了标题,即:
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);
但是,我在服务器响应中没有任何访问控制或附加的头。如果您需要更多信息,请告诉我。请访问。您将获得在WebAPI中实现CORS的完整指南
更新:
要在WEBAPI中实现CORS,请执行以下步骤:
安装软件包Microsoft.AspNet.WebApi.Cors
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
}
}
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class BootStrapController : ApiController
{
// Controller methods
}
根据您的需要,来源、标题和方法可能会有所不同前面的答案是正确的,但是如果您想在所有控制器中启用CORS,可以用一种非常简单的方法:在
WebApiConfig
类中,在Register
方法内,添加下面两行:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// These next two lines enables CORS for all controllers
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
}
请在您的答案中添加更多细节。只有链接的答案不是一件好事。如果链接断开,答案将变为无效。