简体   繁体   中英

Cors issue API not on same server

I'm using Web API 2. in my WebApiConfig, I have this.

   private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var origin = WebConfigurationManager.AppSettings["origin"];
        var cors = new EnableCorsAttribute(

            origins: "*",
            headers: "*",
            methods: "*");
        config.EnableCors(cors);
    }

Register Method

        public static void Register(HttpConfiguration config)
    {

        config.MapHttpAttributeRoutes();
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        EnableCrossSiteRequests(config);

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

From my understanding shouldn't that all I need to for this to work? It's worked on my dev computer when they are hosted together. But now one is on a web server and the API is on a different web server.

I'm getting - Origin ... not found in Access-Control-Allow-Origin header.

I have it set to allow all Origin. I've tried adding it in the web config , and other methods posted around Stack overflow. I don't understand why its being denied?

Front end is Angular, using Ngresource for requests.

If I use the Network Tab in chrome dev tools, the Response to the request is 200 OK, and nothing else happens after that. Been searching all day for solutions, nothing I've tried so far has worked.

Thank you.

From my understanding shouldn't that all I need to for this to work?

Nope. You should decorate the Web API controllers/actions that you would like to be calling cross domain with the [EnableCors] attribute:

[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class MyController: ApiController
{
    ...
}

Here's a good read on this topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM