S
S
stcmd042362017-03-13 17:14:07
ASP.NET
stcmd04236, 2017-03-13 17:14:07

How to properly configure CORS in WebApi?

Good evening! There is a small project which is implemented on Asp NET WebApi. To enable support for cross-domain requests, I installed CORS. The headers are fine. But if you send an OPTIONS request, it gives a 405 error.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Конфигурация и службы Web API
            // Настройка Web API для использования только проверки подлинности посредством маркера-носителя.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Маршруты Web API
            config.MapHttpAttributeRoutes();

            // кроссдоменные запросы
            var cors = new System.Web.Http.Cors.EnableCorsAttribute ( "*", "*", "*" );
            config.EnableCors ( cors );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kvasek, 2017-03-14
@kvasek

Hello, I had a similar problem, only one thing helped me to write CORS in Web.config with handles

<configuration>
  ...
  <system.webServer>
    ...
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="DELETE, GET, HEAD, OPTIONS, POST, PUT" />
        <add name="Access-Control-Allow-Headers" value="Accept, Authorization, Content-Type, Origin, X-Requested-With" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question