0

I have application using MVC, angular.js , entity framework and Webapi. My Webapi is in same solution but in different project so it has its own port. In my angular service i tried to call webapi like

app.service('MyService', function coursesService($http) {
var self = this;

self.addData = function (data, config) {
    return $http.post('http://localhost:1234/api/Test', JSON.stringify(data), config)
   .success(function (data, status, headers, config) {
       return data;
   })
   .error(function (data, status, header, config) {
       return data;
   });
}
});

But when application ran it was throwing error cross origin request. So in my webapi's webapiconfig.cs i had to write below code in Register method

var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

Then i got rid of this error. But what i would like to know if this is common issue and what is best way to avoid it?

James
  • 1,827
  • 5
  • 39
  • 69
  • 2
    Possible duplicate of [CORS error on same domain?](http://stackoverflow.com/questions/19966707/cors-error-on-same-domain) – Paul Abbott Feb 27 '17 at 22:01
  • This is how it is. If you put the web api controllers inside the MVC project, like /Controllers/api, you would not have to enable CORS to hit the API. – Dylan Feb 27 '17 at 22:31
  • The other solution if you want to hide your api, is to post back to your controller and then create a web request to your api using a tool like Refit. This way, if you decide to split your api onto a separate web server, you would only have to change the configuration file that tells re-fit where to find your api end point. – Slicksim Feb 28 '17 at 10:26

0 Answers0