You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8自定义注册模型后,如何移除默认注册端点或合并控制器?

移除ASP.NET Core默认注册端点或合并自定义控制器的规范实现

一、移除默认注册端点

方法1:完全禁用Identity默认API端点

如果你的项目通过MapIdentityApi<TUser>生成了默认身份验证端点(含注册),直接删除这行代码即可。此时Swagger不会再显示默认注册端点,所有身份验证逻辑由自定义控制器接管。

示例代码(Program.cs):

// 移除默认Identity API端点的注册代码
// app.MapIdentityApi<YourCustomUserEntity>();

// 仅保留自定义控制器的路由映射
app.MapControllers();

方法2:移除单个默认端点

若需保留部分默认端点,仅移除注册端点,可通过路由筛选实现。在Program.cs中配置路由时,过滤掉对应端点:

var endpoints = app.MapControllers();

// 移除默认注册端点(默认路径为 /register)
var registerEndpoints = endpoints.Where(e => e.DisplayName?.Contains("Register") == true).ToList();
foreach (var endpoint in registerEndpoints)
{
    endpoint.Dispose();
}

二、合并自定义控制器与默认Identity逻辑

如果不想完全抛弃Identity的成熟用户管理逻辑,可在自定义控制器中注入核心服务复用逻辑,同时保持端点的自定义控制权:

1. 自定义控制器中注入Identity服务

public class CustomAuthController : ControllerBase
{
    private readonly UserManager<YourCustomUserEntity> _userManager;
    private readonly SignInManager<YourCustomUserEntity> _signInManager;

    public CustomAuthController(UserManager<YourCustomUserEntity> userManager, SignInManager<YourCustomUserEntity> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

    // 自定义注册接口,复用Identity的用户创建逻辑
    [HttpPost("custom-register")]
    public async Task<IActionResult> Register([FromBody] CustomRegisterRequest request)
    {
        var user = new YourCustomUserEntity 
        { 
            UserName = request.Email, 
            Email = request.Email,
            // 填充自定义实体的其他字段
            CustomField = request.CustomField
        };

        var createResult = await _userManager.CreateAsync(user, request.Password);
        if (!createResult.Succeeded)
        {
            return BadRequest(createResult.Errors);
        }

        await _signInManager.SignInAsync(user, isPersistent: false);
        return Ok(new { Message = "注册成功", UserId = user.Id });
    }

    // 其他自定义身份验证接口...
}

2. 配置Identity服务(Program.cs)

确保注册Identity核心服务,但不启用默认API端点:

builder.Services.AddIdentityCore<YourCustomUserEntity>(options => 
{
    // 根据需求配置Identity选项,如密码规则、登录验证规则等
    options.Password.RequireDigit = true;
    options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<YourDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();

// 仅映射自定义控制器
app.MapControllers();

这种方式既可以复用Identity的用户创建、密码哈希等成熟逻辑,又能完全控制API的路径、请求参数和响应格式,Swagger中只会显示自定义的端点。

内容的提问来源于stack exchange,提问作者Doğa Koçak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:06:17