Angular 6 Asp.Net(非核心)Web API CORS 请求失败



我正在构建一个将由Angular 6客户端使用的.Net Web Api,但由于任何原因,我无法在我的开发环境中工作。

我从一个非常简单的 Web API 开始,它什么都不做,只是返回一个字符串(前端和后端测试目的之间的通信(:

// GET: api/Login
public IEnumerable<string> Get()
{
return new string[] { "Now it works!" };
}
// POST: api/Login
public void Post([FromBody]string value)
{
string strTest = "I'm doing just nothing";
}

然后在我的 Angular 6 应用程序中,我有一个带有以下 post 请求的方法:

return this.http.post<any>(`http://localhost:9810/api/Login`, { username, password })
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
}));

在我第一次尝试时,我所有的响应都失败了:

区域.js:2969 选项 http://localhost:9810/api/Login 405(方法不允许(
登录:1 加载失败 http://localhost:9810/api/Login:对预检请求的响应未通过访问控制检查:请求的资源上不存在"访问控制-允许源"标头。因此,不允许访问源"http://localhost:4200"。

因此,在调查之后,我以另一种方式将CORS支持添加到我的WebApi .Net项目中:

1( 已安装的 Nuget 包:

Microsoft.AspNet.WebApi.Cors
Microsoft.AspNet.Cors

2( 在 WebApiConfig Register 方法中:

var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
// or var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

3( 替代 2( 在 API 控制器类标头中:

[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]

但是似乎都不起作用,请求总是失败,并出现与浏览器控制台中上述相同的错误。

我尝试创建一个自托管WebApi,监听 http://localhost:9000 上的http调用,以及我最后一次尝试在具有9810端口的本地Windows 10 IIS服务器中发布WebApi。

如果我像"http://localhost/api/Login"一样在浏览器中访问 url,则返回字符串如下:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Now it works!</string>
</ArrayOfstring>

并且控制台中没有显示任何错误,但只要我尝试通过 Angular(默认端口 4200(发出请求,请求就会失败并出现 CORS 错误。

我被卡住了。如果我不能从 Angular 工作,我将无法进行调试和测试。

谢谢。

修改 1:添加了 Chrome 网络标签页信息。

常规:

请求网址:http://localhost:9000/api/Login
请求方法:选项
状态代码:405 方法不允许
远程地址:[::1]:9000
推荐人政策:降级时无引荐来源

网址

响应标头:

允许:获取,发布
内容长度:76
内容类型:应用程序/json; 字符集=utf-8 日期:2018 年 8
月 29 日星期三 10:32:36 GMT
服务器:Microsoft-HTTPAPI/2.0

请求标头:

Accept:

/
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9 访问控制请求
标头:内容类型
访问控制请求方法:开机自检 连接:保持活动状态 主机:

本地主机:9000
来源:http://localhost:4200
用户代理:Mozilla/5.0(Windows NT 10.0;赢64;x64( AppleWebKit/537.36 (KHTML, like Gecko( Chrome/68.0.3440.106 Safari/537.36

在挣扎了整个上午并尝试了你们每个人在这里建议的一切之后,我无法相信最终我的问题可以如此轻松地解决。

关于@Madpop建议Application_BeginRequest(出于任何原因(从未被解雇(不想花太多时间调查原因(。

@Steveland解决方案涉及添加依赖注入,除了我没有使用 Asp.Net Core而是 Asp.Net 框架 4.6 之外,这对我来说有点复杂(我没有太多经验(。

我正在寻找一个简单的解决方案来解决我认为应该很容易解决的问题,并且密钥正在附加

[HttpPost]
[HttpOptions] //this was the key
[Authorize]

到发布方法标头。这是我在请求中允许"选项"动词的唯一方法。

我不知道这是否是实现这一目标的最佳方法,但现在它有效(让我知道你们的想法(。

我感谢大家在这里提供的 ev'ry 帮助并表示感谢,因为我不是这个主题的专家(Angular + Web Api(,我想最后问下一个:

当 api 部署到服务器时,我是否也必须将此 [HttpOptions] 也用于生产,或者现在只需要在本地调试和测试

?编辑 1:

经过测试,我注意到它适用于自托管 Web Api,但是当我将 Web API 发布到我的本地 IIS 时,我在浏览器:(中得到"415 不支持的媒体类型">

关于cors问题,我也遇到了类似的问题,我创建了一个global.asax文件,我放置了以下代码

protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://staging.example.com:8044");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Accepts, Content-Type, Origin, X-My-Header");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "60");
HttpContext.Current.Response.End();
}
}

它在 Angular 6 中也适用于 Ionic 3,在所有这些尝试安装之前 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

上面的Chrome插件并激活它,然后尝试运行该应用程序

最新更新