Cors with MVC5, Webapi and Angular Js

2019-07-13 01:32发布

I'm testing a simple Visual studio solution with two project:

  • project A: web project where there same angular code, i.e login/function to autenticate user (post to account api to project B). Account Api give me token based on user/name.

  • project B: web api where I can get same simple data (http GET), and where there are same account api (i.e. integrated api/token that give me auth token based on credential).

Either project are hosted on the same server but with different name and port: http://web.project.com:1100 and http://webapi.project.com:1101 (common domain project.com).

My problem is about CORS: when try to login an user from projectA with project B I receive

Access-Control-Allow-Origin missing

(in browser console ) from wepabpi.project.com:1101.

This is because domain are hosted in different domain.

I install this package:

Install-Package Microsoft.AspNet.WebApi.Cors 

and I add this line in webapiconfig.cs (register method)

config.enableCors();

and I add this attribute in my api controller:

[EnableCors(origins: "http://web.project.com:1100", headers: "", methods: "")]

First question: Webproject send request by using angularjs http call. When from my browser contact the webproject to http://web.project.com:1100 the page call web api, but the origin is http://web.project.com:1100 or my browser origin? I don't understand if webserver make call with this origin or angular using the browser origin. I don't understand if angular code are running by webserver or browser.

Second question: also add this line to controller and enabled cors, I get the same error. I suppose that token generation need same extra configuration, but where? This because standar token generation is not a specific controller.

Thanks

2条回答
beautiful°
2楼-- · 2019-07-13 02:15

In your backend project (Project B), you only need to set Access-Control-Allow-Origin as * at global level, So basically allowing all other JS to access your REST api.

In file Global.asax.cs import using System.Web; and the add below code :

 protected void Application_BeginRequest(object sender, EventArgs e)
 {
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
 } 
查看更多
Ridiculous、
3楼-- · 2019-07-13 02:19

you will add header in your angularjs service or factory because both are two different projects. and first project code contains local server only.second project code contains remote location so you will add remote location ip address and header file

 this.getloggedInUserData = function() {
    var defer = $q.defer();
    var loggedInUserPromise =http({
    url: "http://192.168.1.8:8080/ABCD1.5/getloggedFarmerData",
    method: "GET",
    headers: {
    'Accept': 'application/json',   'Content-Type': 'application/json'
    }
    });
查看更多
登录 后发表回答