Angular/C#CORS问题 [英] Angular/C# CORS Issue

查看:39
本文介绍了Angular/C#CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将客户端托管在localhost:8080/上,将服务器托管在localhost:44302/

I hosted my client on localhost:8080/ and server on localhost:44302/

我正在尝试链接到我的后端,但是我遇到了CORS问题.以下是我的 Angular http请求

I am trying to link to my backend, but I am getting CORS issue. Below is my Angular http request

$http.post(url, data, {
    headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'POST, OPTIONS'
             }
}).success(function (response) {
  // rest of the code
}).error(function (err, status) {
  // rest of the code
});

在用C#编写的服务器端,我对响应进行了以下设置

On the server side which is written in C#, I have the following set on the response

 Response.ContentType = "application/json";
 Response.AddHeader("Access-Control-Allow-Origin", "*");
 Response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");

即使设置了这些,我仍然遇到以下错误

Even after setting these, I am getting the following error

XMLHttpRequest无法加载 https://localhost:44302/some_uri .请求中不存在"Access-Control-Allow-Origin"标头资源.因此,不允许来源' http://localhost:8080 使用权.响应的HTTP状态代码为400.

XMLHttpRequest cannot load https://localhost:44302/some_uri. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.

我想念什么?

推荐答案

您不需要从AngularJS发送任何其他标头.

You do not need to send any additional headers from AngularJS. Preflight request will be made for you automatically.

要在Web API中启用所有跨域请求,您可以执行以下操作:

To enable all cross-origin requests in Web API, you can do this:

  1. 安装NuGet软件包Microsoft.AspNet.WebApi.Cors.
  2. 将以下代码添加到WebApiConfig.cs:

  1. Install NuGet package Microsoft.AspNet.WebApi.Cors.
  2. Add the following code to WebApiConfig.cs:

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

对CORS的完全理解值得花费几分钟的时间.我建议在这里阅读深入的教程:

Full understanding of CORS is worth a few minutes of time. I recommend reading an in-depth tutorial here:

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

这篇关于Angular/C#CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆