gpt4 book ai didi

c# - 如何将参数传递给 ValidationAttribute?

转载 作者:太空狗 更新时间:2023-10-29 23:15:14 26 4
gpt4 key购买 nike

我有一个自定义的 ValidationAttribute,它检查另一个用户是否已经存在。为此,它需要访问我的数据访问层,一个由 Unity 注入(inject)我的 Controller 的实例

我如何将这个(或与此相关的任何东西)作为参数传递到我的自定义验证器中?

这可能吗?即我在创建 Dal 的地方,这应该是一个参数

public class EmailIsUnique : ValidationAttribute
{
private string _errorMessage = "An account with this {0} already exists";

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DataAccessHelper Dal = new DataAccessHelper(SharedResolver.AppSettingsHelper().DbConnectionString); //todo, this is way too slow
bool isValid = true;
if(value == null) {
isValid = false;
_errorMessage = "{0} Cannot be empty";
} else {
string email = value.ToString();
if (Dal.User.FindByEmail(email) != null)
{
isValid = false;
}
}

if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}

最佳答案

我不太确定您是否能够将运行时参数传递到您的属性中。

你可以使用 DependencyResolver.Current.GetService<DataAccessHelper>()解决你的 dal(假设你已经注册了 DataAccessHelper)

您可能更可能将 DataAccessHelper 注册为 IDataAccessHelper 或其他什么?在这种情况下你会调用GetService<IDataAccessHelper>

public class EmailIsUnique : ValidationAttribute
{
private string _errorMessage = "An account with this {0} already exists";

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IDataAccessHelper Dal = DependencyResolver.Current.GetService<IDataAccessHelper>(); // too slow
bool isValid = true;
if(value == null) {
isValid = false;
_errorMessage = "{0} Cannot be empty";
} else {
string email = value.ToString();
if (Dal.User.FindByEmail(email) != null)
{
isValid = false;
}
}

if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}

public class EmailIsUnique : ValidationAttribute
{
[Dependency]
public IDataAccessHelper DataAccess {get;set;}

private string _errorMessage = "An account with this {0} already exists";

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{

bool isValid = true;
if(value == null)
{
isValid = false;
_errorMessage = "{0} Cannot be empty";
}
else
{
string email = value.ToString();
if (DataAccess.User.FindByEmail(email) != null)
{
isValid = false;
}
}

if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}

关于c# - 如何将参数传递给 ValidationAttribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20757615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com