Angular 6 Asp.Net(非核心)Web Api CORS请求失败 [英] Angular 6 Asp.Net (not Core) Web Api CORS request fails

查看:70
本文介绍了Angular 6 Asp.Net(非核心)Web Api CORS请求失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个.Net Web Api,它将被Angular 6客户端使用,但是由于某种原因,我无法使其在我的开发环境中正常工作.

I'm building a .Net Web Api that will be consumed by Angular 6 client but for any reason I'm not being able to make it to work in my development environment.

我从一个非常简单的Web Api开始,该Web Api什么也不做,只返回一个字符串(具有前端和后端测试目的之间的通信):

I started with an extremely simple Web Api that just does nothing but returns a string (with communication between frontend and backend testing purposes):

// 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应用中,我有一个具有以下发布请求的方法:

and then in my Angular 6 app I have a method with the following post request:

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

在我的第一次尝试中,我的所有回复都失败了,并且回复:

In my first attempts all my responses were failing with response:

zone.js:2969选项 http://localhost:9810/api/Login 405(方法不允许)
login:1无法加载 http://localhost:9810/api/Login :对预检请求的响应没有无法通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:4200 .

zone.js:2969 OPTIONS http://localhost:9810/api/Login 405 (Method Not Allowed)
login:1 Failed to load http://localhost:9810/api/Login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

因此,在调查之后,我已经以下面的方式向我的WebApi .Net项目中添加了CORS支持:

So I after investigating I've added CORS support to my WebApi .Net project the next way:

1)已安装的Nuget软件包:

1) Installed Nuget packages:

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

2)在WebApiConfig注册方法中:

2) In WebApiConfig Register method:

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

3)替代2)在Api控制器类标头中:

3) Alternatively to 2) in Api controller class header:

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

但是似乎没有任何作用,请求总是失败,并显示与浏览器控制台中上述相同的错误.

But none seems to work, the request always fails with the same error as described above in browser console.

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

I tried creating a self hosting WebApi listening http calls on http://localhost:9000 as well as my last attempt that was publishing the WebApi in my local Windows 10 IIS server with 9810 port.

如果我这样访问浏览器中的网址" http://localhost/api/Login ",则这样返回字符串:

If I access the url in browser like so "http://localhost/api/Login" then the string is returned like so:

<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错误.

and no error is displayed in console but as long as I try to make the request by Angular (default port 4200) the request fails with CORS error.

我被困住了.如果我无法使其在Angular上正常工作,我将无法进行调试和测试.

I'm stuck. If I cannot make it to work from Angular I won't be able to do debugging and testing.

谢谢.

添加了Chrome网络标签页信息.

Edit 1: Chrome network tab info added.

常规:

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

Request URL: http://localhost:9000/api/Login
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: [::1]:9000
Referrer Policy: no-referrer-when-downgrade

响应标题:

允许:GET,POST
内容长度:76
内容类型:application/json; charset = utf-8
日期:2018年8月29日,星期三10:32:36 GMT
伺服器:Microsoft-HTTPAPI/2.0

Allow: GET,POST
Content-Length: 76
Content-Type: application/json; charset=utf-8
Date: Wed, 29 Aug 2018 10:32:36 GMT
Server: Microsoft-HTTPAPI/2.0

请求标头:

接受:/
接受编码:gzip,deflate,br
接受语言:es-ES,es; q = 0.9
访问控制请求标头:内容类型
访问控制请求方法:POST
连接:保持活动状态
主机:localhost:9000
来源: http://localhost:4200
用户代理:Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/68.0.3440.106 Safari/537.36

Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:9000
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

推荐答案

整个上午都在努力奋斗,并尝试了每个人在这里提出的建议后,我不敢相信我的问题最终会如此轻松地得到解决.

After struggling my head the whole morning and trying everything each one of you suggested here I cannot believe in the end my problem could have been resolved so easily.

关于@Madpop建议Application_BeginRequest(无论出于何种原因)从未被解雇(不想花很多时间调查原因).

Regarding @Madpop suggestion Application_BeginRequest (for any reason) was never being fired (dind't want to spend much time investigating why).

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

@Steveland solution involved adding dependency injection and it resulted a little bit complicated to me (I don't have much experience with that) aparte from the fact I'm not using Asp.Net Core but Asp.Net framework 4.6.

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

I was looking for a simple solution to a problem I thought it should have been easy to solve and the key was appending

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

发布方法标题.这是我在请求中允许使用选项"动词的唯一方法.

to Post method header. This was the only way for me to allow "Options" verb in request.

我不知道这是否是实现此目标的最佳方法,但目前它有效(让我知道您的想法).

I don't know if this is the best way to accomplish this but for now it works (let me know what d'you think guys).

我非常感谢我在这里收到的每个人的帮助,并表示感谢,由于我不是该主题的专家(Angular + Web Api),所以我想问下一个问题:

I appreciate ev'ry help I've received here from everybody and say thanks and as I'm not an expert on this subject (Angular + Web Api) I would like to finally ask the next:

当将api部署到服务器时,或者在本地进行调试和测试时,现在是否还需要将此[HttpOptions]用于生产?

Will I have to put this [HttpOptions] also for production when the api will be deployed to server or this is just needed for now for debugging and testing locally purposes?

经过测试,我注意到它可以与自托管Web Api一起使用,但是当我将Web Api发布到本地IIS时,我在浏览器中得到"415 Unsupported Media Type":(

After testing I've noticed it works with self hosting Web Api but as I publish Web Api to my local IIS I get "415 Unsupported Media Type" in browser :(

这篇关于Angular 6 Asp.Net(非核心)Web Api CORS请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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