public override void OnParameterInvaliding(HttpActionContext actionContext, ValidationFailedResult result) { var message = result.Data.FirstOrDefault()?.Message; actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, OperatedResult <string> .Fail(message)); }
public void Test_ValidationFailedResult_ToStringEmpty() { // Arrange var modelState = new ModelStateDictionary(); // Act var res = new ValidationFailedResult(modelState); var str = res.ToString(); // Assert str.Should().Be("Validation Error (400): Model could not be validated."); }
/// <summary> /// 在调用操作方法之前发生。 /// </summary> /// <param name="actionContext">操作上下文。</param> public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ActionArguments.Any(kv => kv.Value == null)) { //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, OnParameterIsNull<T>()); OnParameterIsNulling(actionContext); } if (!actionContext.ModelState.IsValid) { ValidationFailedResult _validateFailedResult = new ValidationFailedResult(422, "请求格式正确,但是由于含有语义错误,无法响应。", actionContext.ModelState); OnParameterInvaliding(actionContext, _validateFailedResult); //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, OnParameterInvalid(_validateFailedResult)); } }
/// <summary> /// Called when [action executing]. /// </summary> /// <param name="context">The context.</param> /// <inheritdoc /> public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { var validationFailedResult = new ValidationFailedResult(context.ModelState); if (_logMessage) { var logger = (ILogger)context.HttpContext.RequestServices.GetService(typeof(ILogger)); logger?.LogInformation(validationFailedResult.ToString()); } context.Result = validationFailedResult; } }
public void Test_ValidationFailedResult_ToString() { // Arrange var modelState = new ModelStateDictionary(); modelState.AddModelError("TestKey1", "TestValue1"); modelState.AddModelError("TestKey2", "TestValue2"); // Act var res = new ValidationFailedResult(modelState); var str = res.ToString(); // Assert str.Should().Be("Validation Error (400): Model could not be validated. TestKey1 - TestValue1, TestKey2 - TestValue2"); }
public async void Validate_Ko() { // valide un user vide UserVm userVm = new UserVm(); var validator = new UserValidator(); var results = validator.Validate(userVm); // simul modelstate d'un controller ModelStateDictionary mockModelState = new ModelStateDictionary(); results.AddToModelState(mockModelState, null); // simul ValidationFailedResult // TODO test ValidationFailedResult possible ? var errorVm = new ErrorVm() { Code = ErrorCode.ValidationFailed, ValidationDictionnay = ValidationFailedResult.ToValidation(mockModelState) }; // compare avec format du json attendu string json = JsonConvert.SerializeObject(errorVm); string jsonCheck = @"{ ""code"":6, ""validation"": { ""Email"":[""Email cannot be empty""], ""LastName"":[""LastName cannot be empty""], ""Password"":[""Password cannot be empty""], ""UserName"":[""User Name cannot be empty""], ""FirstName"":[""FirstName cannot be empty""] } }"; bool jsonOk = JToken.DeepEquals(JToken.Parse(json), JToken.Parse(jsonCheck)); Assert.False(mockModelState.IsValid); Assert.True(jsonOk); }
/// <summary> /// 参数验证不通过 /// </summary> /// <param name="actionContext">操作上下文</param> /// <param name="result">ValidationFailedResult</param> public abstract void OnParameterInvaliding(HttpActionContext actionContext, ValidationFailedResult result);
public static void ConfigureStartupServices <TDbContext>(this IServiceCollection services, IConfiguration configuration, string migrationAssemblyName) where TDbContext : DbContext { #region Health checks services.AddHealthChecks() .AddDbContextCheck <TDbContext>(); #endregion #region AppSettings services.Configure <AppSettings>(configuration); AppSettings appSettings = configuration.Get <AppSettings>(); #endregion #region DbContext services.AddFandaDbContextPool <TDbContext>(appSettings, migrationAssemblyName); #endregion #region CORS services.AddCors(options => { var urls = new[] { "http://*****:*****@gmail.com", Url = new Uri("https://twitter.com/tbalakpm"), }, License = new OpenApiLicense { Name = "Use under MIT", Url = new Uri("https://fanda.in/license"), } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.ApiKey, Scheme = "Bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Description = "JWT Authorization header using the Bearer scheme." }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] {} } }); }); #endregion }