我想知道如何使用ASP.NET Web API实现模型验证.我的模型是这样的:
public class Enquiry
{
[Key]
public int EnquiryId { get; set; }
[Required]
public DateTime EnquiryDate { get; set; }
[Required]
public string CustomerAccountNumber { get; set; }
[Required]
public string ContactName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的API控制器中有一个Post动作:
public void Post(Enquiry enquiry)
{
enquiry.EnquiryDate = DateTime.Now;
context.DaybookEnquiries.Add(enquiry);
context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
如何添加if(ModelState.IsValid)然后处理错误消息以传递给用户?
我正在开发一个大型的MVC3 Web应用程序,并对该ModelState.IsValid方法感到烦恼.
几乎所有的控制器都使用ModelState,以验证发布的数据.视图都基于包含不同类的ViewModel,这些类显然包含可以标记为的属性[Required].
我遇到的问题是有时不需要所需的属性,我必须使用该ModelState.Remove方法才能ModelState.IsValid成为现实.
我的问题是使用ModelState.Remove,这是正确的做事方式还是更有效的方法.
任何人都可以解释在代码中使用自定义属性的好处(或原因).当然我在某些场景(WCF,序列化等)中使用(并理解其目的)定义属性,但我无法想象我需要创建和使用自己的自定义属性的任何算法.有人可以提供一个真实案例,其中自定义属性的使用为项目带来了一些东西.
我有一个使用编辑上下文的编辑表单:
<EditForm OnValidSubmit="HandleValidSubmit" EditContext="_editContext" Context="auth">
<DataAnnotationsValidator />
<input type="time" @bind-value="_foodTruck.EndDelivery" @onkeydown="@(q=>ResetValidation("EndDelivery"))" >
<ValidationMessage For="() => _foodTruck.EndDelivery" />
<input type="time" @bind-value="_foodTruck.StartDelivery" @onkeydown="@(q=>ResetValidation("StartDelivery"))" >
<ValidationMessage For="() => _foodTruck.StartDelivery" />
<input class="btn btn-default" type="submit" value="save" />
</EditForm>
Run Code Online (Sandbox Code Playgroud)
我在 HandleValidSubmit 中做了一些自定义验证:
EditContext _editContext = new EditContext(_foodTruck);
private async void HandleValidSubmit()
{
var messageStore = new ValidationMessageStore(_editContext);
if (_foodTruck.StartDelivery >= _foodTruck.EndDelivery)
{
messageStore.Add(_editContext.Field("EndDelivery"), "Bad time entered");
_editContext.NotifyValidationStateChanged();
}
if (!_editContext.Validate()) return;
}
Run Code Online (Sandbox Code Playgroud)
现在发生的是我的自定义错误(“输入的错误时间”)显示在正确的位置。唯一的问题是:当我更改值时,该错误不会消失。因此,如果我单击提交按钮,则永远不会再次调用 HandleValidSubmit。
我还尝试在修改字段时清空验证错误:
protected void ResetValidation(string field)
{
var messageStore = new ValidationMessageStore(_editContext); …Run Code Online (Sandbox Code Playgroud) 是否可以从配置文件加载属性值?例如,我的属性下面有缓存属性返回值.该属性在应用程序中使用了10次以上,我想从配置文件中加载第二个属性参数(1800秒).
[Cache(CacheType.Absolute, 1800, CacheLocation.Memory)]
Run Code Online (Sandbox Code Playgroud) 我想验证日期时间,我的代码是:
[Range(typeof(DateTime),
DateTime.Now.AddYears(-65).ToShortDateString(),
DateTime.Now.AddYears(-18).ToShortDateString(),
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime Birthday { get; set; }
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Run Code Online (Sandbox Code Playgroud)
请帮我?
因此,在使用.NET Membership系统的MVC中,密码策略在web.config文件中定义.例如,minPasswordLength在membership - >配置文件中定义.
使用View时,可以使用该@Membership组件访问它
Passwords must be at least @Membership.MinRequiredPasswordLength characters long.
Run Code Online (Sandbox Code Playgroud)
但是,如果您查看示例MVC应用程序中的默认模型,它会说
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)
我很好奇的部分是MinimumLength = 6因为这是硬编码的,这意味着如果我想更新密码长度,我不仅要编辑web.config(如Microsoft建议),还要搜索任何引用它在源头并在各处变化(可能不是最好的编程实践).
有没有在Attributes中使用变量的方法.我怀疑不是因为这可能发生在编译时而不是运行时.如果没有人知道更好的模式,以阻止我在将来找到替换所有引用?
我装饰了一堂课:
[Required(ErrorMessage = "Price is required.")]
public decimal Price { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是当用代码验证它时:
for each (PropertyInfo prop in Me.GetType().GetProperties())
{
if (prop.GetIndexParameters().Length = 0)
{
for each (ValidationAttribute validatt in prop.GetCustomAttributes(GetType(ValidationAttribute), True))
{
if (!validatt.IsValid(prop.GetValue(Me, Nothing))
{
retval.Add(New PropertyValidationError(prop.Name, string.Format("There is a problem with the {0} property. It is flagged with the {1}", prop.Name, validatt.GetType.Name), validatt.ErrorMessage));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我发现 的值0被视为满足“要求”,这不是我想要的(实际上,我想允许除零以外的任何值) - 是我的验证代码做错了,还是有没有一种方法可以将装饰与 a 一起ValidationAttribute用于值类型的默认值?
c# ×5
validation ×3
asp.net-mvc ×2
.net ×1
attributes ×1
blazor ×1
code-first ×1
date-range ×1
modelstate ×1
razor ×1