2

我已经阅读了关于ASP.NET Core和CORS主题的所有内容,我相信我能理解它的大部分内容,但是,我会如果我能把它工作,那该死的。我使用的是Chrome浏览器,这里是数据:如何让CORS与ASP.Net Core Web API服务器一起工作Angular 2客户端

Prefilght:

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 

帖子:

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: "[email protected]", password: "[email protected]", rememberMe: false} 
    email: "[email protected]" 
    password: "[email protected]" 
    rememberMe: false 
    userName:"" 

ASP.NET核心代码:

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

ASP。 NET核心控制器:

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

这里是角码:

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

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

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. 

请注意,我是从得到一个500错误POST请求。这似乎不像服务器在发生CORS问题时发送的错误。我认为这是另一回事,但是,所有这些代码都在单一域中工作,现在CORS出现了一些问题。无论如何,我已经阅读了一切,我可以找到,没有任何工作。我在想,这可能与WebAPI路线有关。

感谢您的帮助!

+0

您向API发出请求时出现的确切错误是什么?你确定他们是CORS相关的吗? –

+0

我从浏览器的控制台编辑了具有确切错误的问题。不知道问题出在哪里,我不知道如何进一步调试它。我已经在控制器操作方法上设置了一个断点,我可以告诉你我永远不会达到这个断点。谢谢! –

+0

你能用邮递员或类似的应用程序登录吗? –

回答

4

嗯,我花了一天的时间试图找出如何处理几乎相同的问题。我将尝试描述更多信息:

我使用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();  
} 

此代码的工作完美,当我在Visual Studio中运行它。但只要我发表了我的WebAPI项目在IIS上我得到了麻烦:预检要求返回状态“代号:204无内容”,而POST和PUT请求返回“405不允许的方法”

204 status for preflight CORS request

405 error for PUT request

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

为了测试这个事情,从角度和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":"Группа первооткрывателей"})); 

我得从我的角度这个脚本同样的问题客户端页面。比我从相同的原始运行这个脚本WebApi被托管(检查没有COR的webAPI)。我有一个错误,告诉我PUT方法不允许在网站上!

最后,我发现解决方案:问题出在IIS上的WebDAV模块中,与我的RESTful服务冲突。 我删除WEBDAV模块从我的WebAPI的网站在IIS,现在,它完美的作品:

cross-origin put request running from my angular site returns 200 status now

要做到这一点:

  1. 选择你的WebAPI网站上IIS
  2. 开放的 “模块”
  3. 找到并移除WebDAV选项

Re将WebDAV选项从IIS上的处理程序映射移到您的webApi站点。

,如果你想了解WEBDAV和Web API的冲突更多的解释这些话题可能是有用的:

forum iis.netforum asp.net


事实证明,WebDAV的处理器和模块又在IIS后出现下一次发布。因此,为防止现场从这样做,修改的WebAPI应用程序的web.config文件,像这样:

<handlers> 
    <remove name="WebDAV" /> 
</handlers> 
<modules> 
    <remove name="WebDAVModule" /> 
</modules> 

this topic帮我弄明白。

+0

我编辑了答案:添加了关于web.config首选项的信息 –