[英]How to get CORS to work with ASP.Net Core Web API server Angular 2 client
我已經閱讀了有關ASP.NET Core和CORS的所有文章,並且相信我能理解其中的大部分內容,但是,如果我能夠將其投入使用,我將感到非常遺憾。 我正在使用Chrome瀏覽器,以下是數據:
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: "irv@testing.com", password: "!P@ssw0rd", rememberMe: false}
email: "irv@testing.com"
password: "!P@ssw0rd"
rememberMe: false
userName:""
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();
}
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) });
}
這是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());
});
}
我在瀏覽器控制台中遇到的確切錯誤是:
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.
請注意,我從POST請求中收到500錯誤。 如果出現CORS問題,這似乎不是服務器將發送的錯誤。 我認為這是另外一回事,但是,所有這些代碼都在單個域中工作,因為現在CORS成為了麻煩。 無論如何,我已經閱讀了所有可以找到的內容,但沒有任何效果。 我認為這可能與WebAPI路由有關。
謝謝你提供的所有幫助!
好吧,我花了一天的時間來弄清楚如何處理幾乎相同的問題。 我將嘗試描述更多信息:
我使用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中運行該代碼時,它可以完美運行。 但是,一旦我在IIS上發布了WebAPI項目,我就遇到麻煩了:預檢請求返回狀態為“代碼:204 No Content” ,而POST和PUT請求返回了“ 405 Method Not Allowed” :
當應用程序托管在IIS上時, AllowAnyMethod()似乎沒有任何作用,因為如上圖所示,僅允許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":"Группа первооткрывателей"}));
從我的角度客戶端頁面運行此腳本時,我遇到了同樣的問題。 比我從托管WebApi的同一來源運行此腳本(以檢查沒有COR的webAPI)。 我遇到一個錯誤,告訴我現場不允許使用PUT方法!
最后,我找到了解決方案: 問題出在IIS上的WebDAV模塊中,與我的RESTful服務沖突 。 我從IIS上的webAPI網站中刪除了WEBDAV模塊,現在可以正常使用了:
去做這個:
還要從IIS上的處理程序映射中為您的webApi站點刪除WebDAV選項。
如果您想進一步了解WEBDAV和Web API沖突,這些主題可能會很有用:
事實證明,WebDav處理程序和模塊在下一次發布后再次出現在IIS中。 因此,為防止站點執行此操作,請修改WebAPI應用程序的web.config,如下所示:
<handlers>
<remove name="WebDAV" />
</handlers>
<modules>
<remove name="WebDAVModule" />
</modules>
這個話題幫助我弄清楚了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.