Adr*_*ves 0 c asp.net-web-api asp.net-core
我需要发帖或在服务器端进行验证以检查电子邮件是否唯一。
在研究中,我一直做的例子是一个传统的 MVC 应用程序,而不是一个 api。
在许多情况下,我看到 [Remote] https://docs.microsoft.com/pt-br/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#remote-attribute。我尝试按照文档来实现,但是调试验证了控制器中的函数没有被调用。
用户.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; }
...
}
}
Run Code Online (Sandbox Code Playgroud)
用户控制器.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.");
}
...
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都知道如何实现这一点?
看到它没有进展,我决定进行个性化验证。
电子邮件用户唯一属性.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.";
}
}
}
Run Code Online (Sandbox Code Playgroud)
用户.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; }
}
}
...
Run Code Online (Sandbox Code Playgroud)
它有效,但我不知道这是否是最好的方法。
| 归档时间: |
|
| 查看次数: |
4835 次 |
| 最近记录: |