我正在使用ASP.NET Core 2.0默认模型验证,尽管模型中的数据错误,但似乎ModelState.IsValid
始终不正确。
[HttpPost("abc")]
public async Task<IActionResult> Abc([FromBody]AbcViewModel model)
{
if (!ModelState.IsValid) { return BadRequest(ModelState); }
...
}
public class AbcViewModel
{
[Required(ErrorMessage = "Id is required")]
[Range(100, int.MaxValue, ErrorMessage = "Invalid Id")]
public int Id { get; set; }
public bool Status { get; set; }
}
当我从Angular应用程序发布数据时,这些值正在正确映射以建模,但是如果Id
为“ 0”或小于100,则Required
和Range
验证器都不为'正常工作,ModelState.IsValid
始终为真。我想念的是什么?
答案 0 :(得分:2)
如果您使用的是services.AddMvcCore()
,则需要显式设置您的应用程序以使用数据注释执行验证:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddDataAnnotations()
/* etc. */;
}
答案 1 :(得分:1)
我使用了您在模型中定义的相同模型属性,并且面临相同的问题。我对属性进行了一项更改,并在属性上定义了DataMember属性,例如:
import {
ContactInfoComponent,
ContactInfoDetailComponent,
ContactInfoUpdateComponent,
ContactInfoDeletePopupComponent,
ContactInfoDeleteDialogComponent,
InfoRoute
} from './';
@NgModule({
imports: [
// importing routes as a class
InfoRoute,
BurocracyPhoneModule,
FrontendSharedModule
],
declarations: [
ContactInfoComponent,
ContactInfoDetailComponent,
ContactInfoUpdateComponent,
ContactInfoDeleteDialogComponent,
ContactInfoDeletePopupComponent
],
entryComponents: [ContactInfoComponent, ContactInfoUpdateComponent, ContactInfoDeleteDialogComponent, ContactInfoDeletePopupComponent],
providers: [{ provide: JhiLanguageService, useClass: JhiLanguageService }],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class BurocracyContactInfoModule {
constructor(private languageService: JhiLanguageService, private languageHelper: JhiLanguageHelper) {
this.languageHelper.language.subscribe((languageKey: string) => {
if (languageKey !== undefined) {
this.languageService.changeLanguage(languageKey);
}
});
}
}
它正在按预期工作,验证了范围值。尝试此操作,希望它可以解决您面临的问题。
答案 2 :(得分:0)
我也为这个问题而战,在我的案例中,有帮助的是将它添加到ConfigureServices中:
MyDocViewA
请谨慎对待结果-如果要获取自动BadRequest,则必须使用MyDocViewB
attribute。否则,您必须检查var commonKeys = ['a', 'b', 'c'];
array.sort((a, b) => {
var keyA = Object.keys(a).filter(k => !commonKeys.includes(k))[0],
keyB = Object.keys(b).filter(k => !commonKeys.includes(k))[0];
return keyA.localeCompare(keyB);
})
属性。