如何使CORS与ASP.Net Core Web API服务器Angular 2客户端一起使用

Irv*_*ert 2 cors asp.net-core-middleware asp.net-core-webapi angular

我已经阅读了有关ASP.NET Core和CORS的所有文章,并且相信我能理解其中的大部分内容,但是,如果我能够将其投入使用,我该死的。我正在使用Chrome浏览器,以下是数据:

预过滤:

General:
Request URL:http://localhost:34376/api/login
Request Method:OPTIONS
Status Code:204 No Content
Remote Address:[::1]:34376

Response Headers:
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:access-control-allow-origin,content-type
Access-Control-Allow-Origin:http://localhost:3000
Date:Wed, 23 Nov 2016 03:05:00 GMT
Server:Kestrel
Vary:Origin
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcbXZjXFNob3BVc1NlcnZpY2Vcc3JjXFNob3BVc1NlcnZpY2VcYXBpXGxvZ2lu?=

Request Headers:
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:34376
Origin:http://localhost:3000
Referer:http://localhost:3000/authentication
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
Run Code Online (Sandbox Code Playgroud)

发布:

Request URL:http://localhost:34376/api/login
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:[::1]:34376

Response Headers:
view source
Content-Length:0
Date:Tue, 22 Nov 2016 03:11:40 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcbXZjXFNob3BVc1NlcnZpY2Vcc3JjXFNob3BVc1NlcnZpY2VcYXBpXGxvZ2lu?=

Request Headers:
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Access-Control-Allow-Origin:true
Connection:keep-alive
Content-Length:87
Content-Type:application/json
Host:localhost:34376
Origin:http://localhost:3000
Referer:http://localhost:3000/authentication
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36

Request Payload:
view source
{userName: "", email: "irv@testing.com", password: "!P@ssw0rd", rememberMe: false}
   email: "irv@testing.com"
   password: "!P@ssw0rd"
   rememberMe: false
   userName:""
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials().Build() );
    });
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseCors("CorsPolicy");

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core控制器:

[EnableCors("CorsPolicy")]
[Produces("application/json")]
[Route("api/Authentication")]
public class AuthenticationController : Controller
{
    private IUnitOfWork _unitOfWork;
    public AuthenticationController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    [HttpPost]
    [Route("/api/login")]
    public JsonResult Login([FromBody]LoginInfo loginInfo)
    {
        return Json(new { id_token = _unitOfWork.Users.CreateJwt(loginInfo) });
    }
Run Code Online (Sandbox Code Playgroud)

这是Angular代码:

@Injectable()
export class AuthenticationService {
private _currentAdminMode: boolean = false;

constructor(private _http: Http, private _config: ConfigurationService) {
}

public login(logInfo: LoginInfo): Observable<TokenContainer> {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    //return an observable
    return this._http.post(this._config.hostPrefix + '/api/login', JSON.stringify(logInfo), { headers: headers })
        .map((response) => {
            return <TokenContainer>(response.json());
        });
}
Run Code Online (Sandbox Code Playgroud)

我在浏览器控制台中遇到的确切错误是:

XMLHttpRequest cannot load http://localhost:34376/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
Run Code Online (Sandbox Code Playgroud)

请注意,我从POST请求中收到500错误。如果出现CORS问题,这似乎不是服务器将发送的错误。我认为这是另外一回事,但是,所有这些代码都在单个域中工作,因为现在CORS有点麻烦了。无论如何,我已经阅读了所有可以找到的内容,但没有任何效果。我认为这可能与WebAPI路由有关。

谢谢你提供的所有帮助!

Joh*_*rog 5

好吧,我花了一天的时间来弄清楚如何处理几乎相同的问题。我将尝试描述更多信息:

我使用netcoreapp1.0,基于IIS的WebAPI的RESTful服务。前端:angular2。

在我的Startup.cs中:

// this is not much important, you can organize builder in Configure method, calling app.UseCors()
public void ConfigureServices(IServiceCollection services)
{   
    services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:37885")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
    services.AddMvc();  
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("AllowSpecificOrigin");
    app.UseMvc();    
}
Run Code Online (Sandbox Code Playgroud)

当我在Visual Studio中运行该代码时,它可以完美运行。但是,一旦我在IIS上发布了WebAPI项目,我就遇到了麻烦:预检请求返回状态为“代码:204 No Content”,而POST和PUT请求返回了“ 405 Method Not Allowed”

飞行前CORS请求的204状态

PUT请求的405错误

这似乎是AllowAnyMethod()没有任何影响,当应用程序是在IIS托管,因为只有GET,HEAD,OPTIONS,TRACE允许我们可以从上面的图片中看到。

为了测试该东西并消除对angular和Web API的怀疑,我创建了测试脚本并在Chrome开发者控制台中运行了它:

var xmlHttp = new XMLHttpRequest(); //returns a XMLHttpRequest object
xmlHttp.open('PUT', "http://localhost:27895/api/usergroups/58c624eb54d98519e85c5771", true);
xmlHttp.setRequestHeader('Content-Type', "application/json");  
xmlHttp.send(JSON.stringify({"id":"58c624eb54d98519e85c5771","Name":"?????? ?????????????????"}));
Run Code Online (Sandbox Code Playgroud)

从我的角度客户端页面运行此脚本时,我遇到了同样的问题。比我从托管WebApi的同一来源运行此脚本(以检查没有COR的webAPI)。我遇到一个错误,告诉我现场不允许使用PUT方法!

最后,我找到了解决方案:问题出在IIS上的WebDAV模块中,与我的RESTful服务冲突。我从IIS上的webAPI网站中删除了WEBDAV模块,现在可以正常使用了:

从我的角度站点运行的跨域放置请求现在返回200状态

去做这个:

  1. 在IIS上选择WebAPI网站
  2. 打开“模块”
  3. 查找并删除WebDAV选项

还要从IIS上的处理程序映射中为您的webApi站点删除WebDAV选项。

如果您想进一步了解WEBDAV和Web API冲突,这些主题可能会很有用:

论坛iis.net论坛asp.net


事实证明,WebDav处理程序和模块在下一次发布后再次出现在IIS中。因此,为防止站点执行此操作,请修改WebAPI应用程序的web.config,如下所示:

<handlers>
   <remove name="WebDAV" />
</handlers>
<modules>
   <remove name="WebDAVModule" />
</modules>
Run Code Online (Sandbox Code Playgroud)

这个话题帮助我弄清楚了。