我是初学者,学习asp核心API,使用程序邮递员时出现错误 类启动
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using project7.Models;
namespace project7
{
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)
{
services.AddControllers();
services.AddDbContext<ApplicationDb>(option => option.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
// services.AddDefaultIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDb>();
// _ = (services.AddIdentity<IdentityUser, IdentityRole>()..AddEntityFrameworkStores<ApplicationDb>().AddDefaultTokenProviders());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
AccountController类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using project7.Models;
using project7.ModelViews;
namespace project7.Controllers
{
[Route("[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly ApplicationDb _db;
private readonly UserManager<ApplicationUser> _manager;
public AccountController(ApplicationDb db, UserManager<ApplicationUser> manger)
{
_db = db;
_manager = manger;
}
[HttpPost]
[Route("Register")]
public async Task<IActionResult> Register(ResgisterModel model)
{
if( model == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
if (EmailExistes(model.Email))
{
return BadRequest("Email is not avalibel");
}
var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email,
PasswordHash = model.Password
};
var result = await _manager.CreateAsync(user);
if( result.Succeeded)
{
return StatusCode(StatusCodes.Status200OK);
}
else
{
return BadRequest(result.Errors);
}
}
return StatusCode(StatusCodes.Status400BadRequest);
}
private bool EmailExistes(string email)
{
return _db.Users.Any(x=>x.Email == email );
}
}
}
此类ApplicationDb
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace project7.Models
{
public class ApplicationDb : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
public ApplicationDb(DbContextOptions<ApplicationDb> option) : base(option)
{
}
}
}
我试图从Postman发送一个帖子到链接“ https://本地主机:44371 /帐户/注册”。这条消息出现在我身上。
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[project7.Models.ApplicationUser]' while attempting to activate 'project7.Controllers.AccountController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 71
Content-Type: application/json
Host: localhost:44371
User-Agent: PostmanRuntime/7.24.1
Postman-Token: 858f3f5f-aa63-47ac-bb8e-c62686d6a651
在ApplicationUser类中有以下代码:
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace project7.Models
{
public class ApplicationUser: IdentityUser
{
public string Country { get; set; }
}
}
在ApplicationUser类中有以下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace project7.ModelViews
{
public class ResgisterModel
{
[StringLength(256),Required]
public string Email { get; set; }
[StringLength(256), Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
}
我看过以前的解决方案,但是对代码无效。
答案 0 :(得分:1)
通常您在启动时错过了服务注册,请使用AddDefaultIdentity注册服务
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();