我需要发帖或在服务器端进行验证以检查电子邮件是否唯一。
在研究中,我一直做的例子是一个传统的 MVC 应用程序,而不是一个 api。
在很多情况下,我看到 [Remote] https://learn.microsoft.com/pt-br/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#remote-attribute .尝试按照文档实现,调试发现controller中的函数都没有被调用。
用户.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Mvc;
namespace Base.Models
{
[Table("users")]
public partial class User
{
...
[Required]
[EmailAddress]
[Remote(action: "VerifyEmail", controller: "UserController",ErrorMessage="Email already in use")]
[Column("email", TypeName = "varchar(254)")]
public string Email { get; set; }
...
}
}
用户 Controller .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Base.Models;
namespace Base.Controllers
{
[Route("api/users")]
[ApiController]
public class UserController : Controller
{
...
[AcceptVerbs("Get")]
public IActionResult VerifyEmail(string email)
{
//forcing it to go wrong
return Json($"Email {email} is already in use.");
}
...
}
}
有人知道如何实现吗?
最佳答案
看到它没有进展,我决定进行个性化验证。
EmailUserUniqueAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Base.Models;
namespace Core.Models
{
public class EmailUserUniqueAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var _context = (AppDbContext)validationContext.GetService(typeof(AppDbContext));
var entity = _context.Users.SingleOrDefault(e => e.Email == value.ToString());
if (entity != null)
{
return new ValidationResult(GetErrorMessage(value.ToString()));
}
return ValidationResult.Success;
}
public string GetErrorMessage(string email)
{
return $"Email {email} is already in use.";
}
}
}
用户.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Mvc;
namespace Base.Models
{
[Table("users")]
public partial class User
{
...
[Required]
[EmailAddress]
[EmailUserUnique]
[Column("email", TypeName = "varchar(254)")]
public string Email { get; set; }
}
}
...
它有效,但我不知道这是否是最好的方法。
关于c - 如何验证电子邮件属性在 ASP .NET CORE API 中是否唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565612/