.NET ComponentModel.DataAnnotations RegularExpression 不适用于 BsonIgnoreExtraElements

.NET ComponentModel.DataAnnotations RegularExpression not working with BsonIgnoreExtraElements

提问人:goodmayhem 提问时间:10/5/2023 更新时间:10/5/2023 访问量:11

问:

我必须将 DataAnnotations 放在某些字段上,以阻止在 API 请求中传递的脚本。 我正在使用正则表达式注释,它在 3 个模型类中工作,但是,它不适用于以下类。

[BsonIgnoreExtraElements]
    public class Folder
    {
        private string _path = "";
        /// <summary>
        /// Unique identifier of the tenant.
        /// </summary>
        [Required]
        public int TenantId { get; set; }  
        /// <summary>
        /// Unique identifier of the folder.
        /// </summary>
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string _id { get; set; }
        /// <summary>
        /// Name of the folder.
        /// </summary>
        [RegularExpression("^[a-zA-Z0-9 ]*$", ErrorMessage = "Name must be alphanumeric")] 
        public string Name { get; set; }    
        /// <summary>
        /// Description of the folder.
        /// </summary>
        [RegularExpression("^[a-zA-Z0-9., ]*$", ErrorMessage = "Description can contain Alphabets, Numbers, Fullstop and Comma only.")]
        public string Description { get; set; }
        /// <summary>
        /// Name of the group for the folder. In case of multiple folder belongs to same group. 
        /// </summary>
        [RegularExpression("^[a-zA-Z0-9 ]*$", ErrorMessage = "GroupName must be alphanumeric")]
        public string GroupName { get; set; }

我认为这是因为 BsonIgnoreExtraElements,这在其他 Model 类中不存在。 该模型的控制器在下面共享。

[ApiExplorerSettings(IgnoreApi = true)]
    [AdminAccessFilter]
    [HttpPut]
    [PUT("tenants/{tenantId}/collab/v1/folders/{folderId}")]
    public async Task<Folder> EditFolderAsync(int tenantId, string folderId, Folder folder)
    {
        folder.FullPath = (!string.IsNullOrWhiteSpace(folder.GroupName) ? (folder.GroupName + "/") : "") + (!string.IsNullOrWhiteSpace(folder.Path) ? (folder.Path + "/") : "") + folder.Name;

在上面的 PUT API 中调用了相同的文件夹模型类,但不会抛出验证错误!为什么 Name、Description 和 GroupName 的 RegularExpression 注解不起作用?请帮忙!

.NET 正则表达式 数据批注 BSON

评论


答: 暂无答案