【发布时间】:2018-05-07 16:23:14
【问题描述】:
Asp.Net Core 2.0 的新手并关注 https://medium.com/@lugrugzo/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8 文章以完成基于 Mysql JWT 的身份验证。
尝试运行项目时出现此错误:
在 Program.cs 中
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
我收到此错误:
error CS0119: 'Startup' is a type, which is not valid in the given context
以及添加一些块后的 Startup 类,如下所示: 在 Startup.cs 中
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// ===== Add our DbContext ========
services.AddDbContext<ApplicationDbContext>();
// ===== Add Identity ========
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// ===== Add Jwt Authentication ========
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
ClockSkew = TimeSpan.Zero // remove delay of token when expire
};
});
// ===== Add MVC ========
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ApplicationDbContext dbContext
)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// ===== Use Authentication ======
app.UseAuthentication();
app.UseMvc();
// ===== Create tables ======
dbContext.Database.EnsureCreated();
}
}
两个文件; Program.cs 和 Startup.cs 属于同一个命名空间。
我无法确切地弄清楚是什么代码块造成了问题。我认为这些错误应该经常出现。所以,也请告诉我是否有办法检测它。
【问题讨论】:
-
要么您有两种类型,称为 Startup(即可能是结构和类),要么您正在尝试将命名空间用作泛型类型。导入启动类所在的正确命名空间或使用完整的限定名称应该可以工作
-
你可以下载repo并构建它吗?我猜你有两个启动文件,但我不确定。
-
@OzgurGUL 我下载了存储库并运行,得到了同样的错误。
-
我试图重现您的问题,但我无法得到任何错误。
-
@OzgurGUL 有没有像这篇文章中提到的那样为 npm 做些什么:github.com/MarkPieszak/aspnetcore-angular2-universal/issues/344
标签: mysql asp.net-web-api asp.net-core jwt