【发布时间】:2021-07-25 16:31:39
【问题描述】:
我一直在努力解决这个问题,我在网上查找了相关信息。我无法解决这个问题。
我的应用程序确实使用了一个已经作为该项目模板存在的 Web API。我认为这可能是导致问题的原因。我对此没有太多经验,而且我没有办法解决这个问题。
另一个问题是如何在没有激活 Web API 配置的情况下使用其他控制器。
网页显示错误的 url: https://localhost:(number removed)/api
如果有人需要查看任何其他代码,请询问,我将编辑帖子,因为我不太确定需要查看所有代码的位置。
我的启动文件:
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 Cookie Authentication via extension method **
//services.AddCookieAuthentication();
// ** Add Cookie and Jwt Authentication via extension method **
services.AddCookieAndJwtAuthentication(Configuration);
// ** Enable Cors for and webapi endpoints provided **
services.AddCors();
// Add UserService to DI - change to use real UserService
services.AddTransient<SolutionNameService,SolutionNameServiceDb>();
// ** Required to enable asp-authorize Taghelper **
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider provider)
{
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
// seed users - using service provider to get UserService from DI
Seeder.Seed(provider.GetService<SolutionNameService>());
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// ** configure cors to allow full cross origin access to any webapi end points **
app.UseCors(c => c.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
// ** turn on authentication/authorisation **
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
程序文件
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
ApiUserController
// ** This is a Demo WebAPI Controller provides User Login Using JWT Token **
[ApiController]
[Route("api")]
// set default auth scheme as we are using both cookie and jwt authentication
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class UserApiController : ControllerBase
{
private readonly IPatientHutService _svc;
private readonly IConfiguration _config; // jwt settings
public UserApiController(IPatientHutService service, IConfiguration _configuration)
{
_config = _configuration;
_svc = service;
}
// POST api/login
[AllowAnonymous]
[HttpPost("login")]
public ActionResult<User> Login(UserLoginViewModel login)
{
var user = _svc.Authenticate(login.Email, login.Password);
if (user == null)
{
return BadRequest(new { message = "Email or Password are incorrect" });
}
// sign jwt token to use in secure api requests
var authUser = SignInJwt(user);
return Ok(authUser);
}
// POST api/login
[AllowAnonymous]
[HttpPost("register")]
public ActionResult<User> Register(UserRegisterViewModel reg)
{
var user = _svc.AddUser(reg.Name, reg.Email, reg.Password, reg.Role);
if (user == null)
{
return BadRequest(new { message = "User Could not be Registered" });
}
// sign jwt token to use in secure api requests
var authUser = SignInJwt(user);
return Ok(authUser);
}
// Sign user in using JWT authentication
private UserAuthenticatedViewModel SignInJwt(User user)
{
return new UserAuthenticatedViewModel
{
Id = user.Id,
Name = user.Name,
Email = user.Email,
Role = user.Role,
Token = AuthBuilder.BuildJwtToken(user, _config),
};
}
}
【问题讨论】:
-
你能发布异常堆栈跟踪或屏幕错误吗?
-
@GabrielFrancisco 当我构建项目时,没有发现任何问题或显示任何错误,但 google 上的网页显示 500 错误并说 localhost 无法处理该错误。如果视觉工作室中有另一种方法可以解决您的问题。让我知道,我会立即发布
-
感觉像是启动失败,因为Configure中的GetRequiredService调用非常可疑。如果这是原因,那么在 Configure 方法的签名中,您可以像这样依赖注入服务:`Configure(INeeededDependency, IOtherStuff)
-
HTTP 状态码 500 表示“服务器内部错误”,您应该检查该错误信息。
标签: c# asp.net-core asp.net-core-webapi