asp.net core 2.0に基づいたASP.NET Boilerplateフレームワークを使用してWebアプリケーションを開発しています。 http://localhost:4200にアクセスすると、ブラウザのコンソールで次のエラーが表示されます。解決方法ASP.NETのBoilerplateで、要求されたリソースに 'Access-Control-Allow-Origin'ヘッダーが存在しませんか?
を有し2:22742/AbpUserConfiguration/GETALL:1つのGET http://localhost:22742/AbpUserConfiguration/GetAll 500(内部 サーバーエラー)はlocalhost /:1 http://localhost:22742/AbpUserConfiguration/GetAllのロードに失敗しました:いいえ 'アクセス制御 - 許可原点' ヘッダが上に存在しますリクエストされた リソース。したがって、「http://localhost:4200」の原点は許可されません。 応答は、HTTPステータスコード500
Logs.txt含量:
INFO 2017年12月14日17:38:21091 [21] soft.AspNetCore.Hosting.Internal.WebHost -要求開始http://localhost:22742/AbpUserConfiguration/GetAll INFO 2017-12-14 17:38:21,148 [21] pNetCore.Cors.Infrastructure.CorsService - ポリシー実行に成功しました。情報2017-12-14 17:38:21,589 [21] soft.AspNetCore.Hosting.Internal.WebHost - 要求は で終了416.2933ms 204 INFO 2017-12-14 17:38:22,414 [21] soft.AspNetCore.Hosting 38:: - ポリシーの実行に成功 22597 [21] pNetCore.Cors.Infrastructure.CorsService - .Internal.WebHostは、HTTP/1.1 がhttp://localhost:22742/AbpUserConfiguration/GetAll アプリケーション/ JSON INFO 2017年12月14日17をGET開始要求します。 INFO 2017-12-14 17:38:22,644 [21] uthentication.JwtBearer.JwtBearerHandler - トークンを検証しました。 INFO 2017-12-14 17:38:22,694 [21] uthentication.JwtBearer.JwtBearerHandler - AuthenticationScheme: ベアラが正常に認証されました。 INFO 2017-12-14 17:38:22,737 [21] pNetCore.Cors.Infrastructure.CorsService - ポリシー実行 が成功しました。 INFO 2017-12-14 17:38:22,849 [21] ore.Mvc.Internal.ControllerActionInvoker - アクションメソッドの実行 Abp.AspNetCore.Mvc.Controllers.AbpUserConfigurationController.GetAll引数を含む (Abp.AspNetCore)((null) ) - ModelStateが有効です。INFO 2017-12-14 17:38:32,529 [23] issues.Json.Internal.JsonResultExecutor - 値Abp.Web.Models.AjaxResponseを作成してJsonResultを実行しています。 INFO 2017-12-14 17:38:32,541 [23] ore.Mvc.Internal.ControllerActionInvoker - 実行されたアクション Abp.AspNetCore.Mvc.Controllers.AbpUserConfigurationController.GetAll 9816.8741msの (Abp.AspNetCore)INFO 2017-12 -14 17:38:32,554 [23] soft.AspNetCore.Hosting.Internal.WebHost - 要求が完了しました 10382.9474ms 200 application/json; charset = utf-8 INFO 2017-12-14 17:38:32,926 [14] soft.AspNetCore.Hosting.Internal.WebHost - HTTP/1.1を開始する を要求するオプションhttp://localhost:22742/api/services/app ... フォーメーションINFO 2017-12-14 17: 38:32,927 [14] pNetCore.Cors.Infrastructure.CorsService - ポリシー実行 が成功しました。 INFO 2017-12-14 17:38:32,941 [14] soft.AspNetCore.Hosting.Internal.WebHost - 要求は 4.2417ms 204 INFO 2017-12-14 17:38:32,948 [14] soft.AspNetCoreで終了しました。 Hosting.Internal.WebHost - HTTP/1.1を開始するリクエスト GET http://localhost:22742/api/services/app ...フォーメーション application/json INFO 2017-12-14 17:38:32,950 [14] pNetCore.Cors.Infrastructure。CorsService - ポリシー実行 が成功しました。 INFO 2017-12-14 17:38:32,957 [14] uthentication.JwtBearer.JwtBearerHandler - トークンの検証に成功しました。 INFO 2017-12-14 17:38:32,960 [14] uthentication.JwtBearer.JwtBearerHandler - AuthenticationScheme: ベアラが正常に認証されました。情報2017-12-14 17:38:32,968 [14] pNetCore.Cors.Infrastructure.CorsService - ポリシー実行 が成功しました。 INFO 2017-12-14 17:38:33,004 [14] ore.Mvc.Internal.ControllerActionInvoker - アクションメソッドの実行 Nec.Stanchion.Sessions.SessionAppService.GetCurrentLoginInformations引数を含む (Nec.Stanchion.Application)(null) ) - ModelStateは です。有効なエラー2017-12-14 17:38:33,466 [21] Mvc.ExceptionHandling.AbpExceptionFilter - 現在のユーザーがいません! System.Exception:現在のユーザーがいません! CでNec.Stanchion.StanchionAppServiceBase.d__9.MoveNext() で:ソース\レポ\ \ユーザー\ \ viveknunaスタンション\ ASPNETコア\ SRC \ Nec.Stanchion.Application \ StanchionAppServiceBase.cs:ライン 36 - - 例外がスローされた--- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(で) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(タスク タスク)で でAbp.Threading前の場所からスタックトレースの終わり.InternalAsyncHelper.d__5
1.MoveNext() in D:\Github\aspnetboilerplate\src\Abp\Threading\InternalAsyncHelper.cs:line 120 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter
のNec.Stanchion.Sessions.SessionAppService.d__0.MoveNext()の の1.GetResult()C:¥Users¥viveknuna¥source¥repos¥Stanchion¥aspnet-c ore \ src \ Nec.Stanchion.Application \ Sessions \ SessionAppService.cs:行44 ---例外がスローされた前の場所からのスタックトレースの終了--- でSystem.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() lambda_method Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvokerでMicrosoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResultで(閉鎖、Object)を()で System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(タスク タスク)。 d__12.MoveNext() ---例外がスローされた前の場所からのスタックトレースの終了--- でSystem.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() にSystem.Runtime.CompilerS System.Runtimeで Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNextでervices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(タスク タスク)() ---例外がスローされた以前の位置からスタックトレースの終わり--- Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(次の状態& 、スコープ&範囲、オブジェクトに Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrowで.ExceptionServices.ExceptionDispatchInfo.Throw()(ActionExecutedContext コンテキスト) &状態、ブール& isCompleted) でMicrosoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificationで__14.MoveNext例外がスローされた--- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(で前の場所からスタックトレースの() ---完)(タスク 実行たObjectResult、 書き込み値マイクロソフト - 33473 [21] etCore.Mvc.Internal.ObjectResultExecutor:38: Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__23.MoveNext() INFO 2017年12月14日17時タスク) .AspNetCore.Mvc.ControllerContext。INFO 2017-12-14 17:38:33,494 [21] ore.Mvc.Internal.ControllerActionInvoker - 実行されたアクションNec.Stanchion.Sessions.SessionAppService.GetCurrentLoginInformations(Nec.Stanchion.Application)in 505.7051ms INFO 2017-12 -14 17:38:33,707 [21] soft.AspNetCore.Hosting.Internal.WebHost - 要求が完了しました 588.0669ms 500 application/json;文字セット= UTF-8
Startup.cs:
using System;
using System.Linq;
using Abp.AspNetCore;
using Abp.AspNetZeroCore.Web.Authentication.JwtBearer;
using Abp.Castle.Logging.Log4Net;
using Abp.Dependency;
using Abp.Extensions;
using Abp.Hangfire;
using Abp.Timing;
using Castle.Facilities.Logging;
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MyCompany.MyProject.Authorization;
using MyCompany.MyProject.Authorization.Roles;
using MyCompany.MyProject.Authorization.Users;
using MyCompany.MyProject.Configuration;
using MyCompany.MyProject.EntityFrameworkCore;
using MyCompany.MyProject.Identity;
using MyCompany.MyProject.Install;
using MyCompany.MyProject.MultiTenancy;
using MyCompany.MyProject.Web.Authentication.JwtBearer;
using PaulMiami.AspNetCore.Mvc.Recaptcha;
using Swashbuckle.AspNetCore.Swagger;
using MyCompany.MyProject.Web.IdentityServer;
#if FEATURE_SIGNALR
using Abp.Owin;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;
using Owin.Security.AesDataProtectorProvider;
using Abp.Web.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Abp.AspNetZeroCore.Web.Owin;
#endif
namespace MyCompany.MyProject.Web.Startup
{
public class Startup
{
private const string DefaultCorsPolicyName = "localhost";
private readonly IConfigurationRoot _appConfiguration;
public Startup(IHostingEnvironment env)
{
_appConfiguration = env.GetAppConfiguration();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//MVC
services.AddMvc(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
});
//Configure CORS for angular2 UI
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
//App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
builder
//.WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray())
.AllowAnyOrigin() //TODO: Will be replaced by above when Microsoft releases microsoft.aspnetcore.cors 2.0 - https://github.com/aspnet/CORS/pull/94
.AllowAnyHeader()
.AllowAnyMethod();
});
});
IdentityRegistrar.Register(services);
AuthConfigurer.Configure(services, _appConfiguration);
//Identity server
if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
{
IdentityServerRegistrar.Register(services, _appConfiguration);
}
//Swagger - Enable this line and the related lines in Configure method to enable swagger UI
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "MyProject API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
});
//Recaptcha
services.AddRecaptcha(new RecaptchaOptions
{
SiteKey = _appConfiguration["Recaptcha:SiteKey"],
SecretKey = _appConfiguration["Recaptcha:SecretKey"]
});
//Hangfire (Enable to use Hangfire instead of default job manager)
//services.AddHangfire(config =>
//{
// config.UseSqlServerStorage(_appConfiguration.GetConMyCompanytionString("Default"));
//});
//Configure Abp and Dependency Injection
return services.AddAbp<MyProjectWebHostModule>(options =>
{
//Configure Log4Net logging
options.IocManager.IocContainer.AddFacility<LoggingFacility>(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Initializes ABP framework.
app.UseAbp(options =>
{
options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization
});
app.UseCors(DefaultCorsPolicyName); //Enable CORS!
app.UseAuthentication();
app.UseJwtTokenMiddleware();
if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
{
app.UseJwtTokenMiddleware("IdentityBearer");
app.UseIdentityServer();
}
app.UseStaticFiles();
if (DatabaseCheckHelper.Exist(_appConfiguration["ConMyCompanytionStrings:Default"]))
{
app.UseAbpRequestLocalization();
}
#if FEATURE_SIGNALR
//Integrate to OWIN
app.UseAppBuilder(ConfigureOwinServices);
#endif
//Hangfire dashboard & server (Enable to use Hangfire instead of default job manager)
//app.UseHangfireDashboard("/hangfire", new DashboardOptions
//{
// Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard) }
//});
//app.UseHangfireServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "defaultWithArea",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject API V1");
}); //URL: /swagger
}
#if FEATURE_SIGNALR
private static void ConfigureOwinServices(IAppBuilder app)
{
GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator),() => new SignalRAssemblyLocator());
app.Properties["host.AppName"] = "MyProject";
app.UseAbp();
app.UseAesDataProtectorProvider();
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
#endif
}
}
AuthConfigurer.cs:
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Runtime.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace MyCompany.MyProject.Web.Startup
{
public static class AuthConfigurer
{
public static void Configure(IServiceCollection services, IConfiguration configuration)
{
var authenticationBuilder = services.AddAuthentication();
if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
{
authenticationBuilder.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = configuration["Authentication:JwtBearer:Audience"],
// Validate the token expiry
ValidateLifetime = true,
// If you want to allow a certain amount of clock drift, set that here
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = QueryStringTokenResolver
};
});
}
if (bool.Parse(configuration["IdentityServer:IsEnabled"]))
{
authenticationBuilder.AddIdentityServerAuthentication("IdentityBearer", options =>
{
options.Authority = configuration["App:ServerRootAddress"];
options.RequireHttpsMetadata = false;
});
}
}
/* This method is needed to authorize SignalR javascript client.
* SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */
private static Task QueryStringTokenResolver(MessageReceivedContext context)
{
if (!context.HttpContext.Request.Path.HasValue ||
!context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
{
//We are just looking for signalr clients
return Task.CompletedTask;
}
var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault();
if (qsAuthToken == null)
{
//Cookie value does not matches to querystring value
return Task.CompletedTask;
}
//Set auth token from cookie
context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
return Task.CompletedTask;
}
}
}
ABPのバージョン:3.2.5 プロジェクトのバージョン:5.0.4
回答を受け入れたものとしてマークしてください。 – aaron