Я пытаюсь включить перекрестный запрос источника для сборки Api в WebAPI 2. Я пробовал некоторые решения стека, но не смог решить проблему.
Ошибка, которую я получаю в консоли браузера -
Access to XMLHttpRequest at 'http://localhost:50981/api/Companies/3' from origin 'http://localhost:64943' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Пожалуйста, найдите мой код ниже -
Код WebApiConfig -
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
//Enable Cors
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Код класса Startup.cs -
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Enable CORS (cross origin resource sharing) for making request using browser from different domains
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
//The Path For generating the Toekn
TokenEndpointPath = new PathString("/token"),
//Setting the Token Expired Time (24 hours)
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
//MyAuthorizationServerProvider class will validate the user credentials
Provider = new MyAuthorizationServerProvider()
};
//Token Generations
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
Код Web.config - Если я Добавьте приведенный ниже код в web.config, как предложено в некоторых ответах на stackoverflow, тогда он даст мне ошибку, приведенную ниже - Код -
<system.webServer>
<!--<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:64943" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>-->
Ошибка -
Access to XMLHttpRequest at 'http://localhost:50981/api/Companies/3' from origin 'http://localhost:64943' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:64943, http://localhost:64943', but only one is allowed.
код На контроллере API -
[EnableCors(origins: "http://localhost:64943", headers: "*", methods: "*")
public class CompaniesController : ApiController