Cors with MVC5, Webapi and Angular Js

南笙酒味 提交于 2019-12-11 03:52:40

问题


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


回答1:


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'
    }
    });



回答2:


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", "*");
 } 


来源:https://stackoverflow.com/questions/44151963/cors-with-mvc5-webapi-and-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!