使用WebApi [Route]属性时,c# – FluentValidation不起作用

前端之家收集整理的这篇文章主要介绍了使用WebApi [Route]属性时,c# – FluentValidation不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的WebApi项目控制器中成功实现了FluentValidation,该控制器只有一个HttpGet方法.当我添加另一个HttpGet方法时,我将路由属性添加到两个方法中.即[Route(“Method1”)]和[Route(“Method2”)].

现在无论我是否输入任何数据,ModelState都会返回true.

这是我的代码.

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.Filters.Add(new ValidateModelStateFilter());

        //FluentValidation
        FluentValidationModelValidatorProvider.Configure(config);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",routeTemplate: "{action}/{id}",defaults: new { controller = "Menu",id = RouteParameter.Optional}
        );


    }
}

ValidateModelStateFilter

public class ValidateModelStateFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest,actionContext.ModelState);
        }
    }
}

调节器

[HttpGet]
[Route("Method1")]
public IHttpActionResult ReadAllMenusByApplication([FromUri] ReadAllMenusByApplicationInput input)
{
        var result = new List<ApplicationMenu>();
        ...
}

输入对象

using FluentValidation;
using FluentValidation.Attributes;

namespace MenuService.Models
{
[Validator(typeof(ReadAllMenusByApplicationInputValidator))]
public class ReadAllMenusByApplicationInput
{
    public ReadAllMenusByApplicationInput() {
        this.ApplicationName = string.Empty;
    }

    /// <summary>
    /// The MenuSystem name of the application
    /// </summary>
    public string ApplicationName { get; set; }
}

public class ReadAllMenusByApplicationInputValidator : AbstractValidator<ReadAllMenusByApplicationInput>
{
    public ReadAllMenusByApplicationInputValidator()
    {
        RuleFor(x => x.ApplicationName).NotEmpty();
    }
}

}

解决方法

使用本文作为参考

Custom Validation in ASP.NET Web API with FluentValidation

您似乎已经完成了所引用文章中的大部分内容.

检查配置顺序.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Web API configuration and services
        config.Filters.Add(new ValidateModelStateFilter());

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",id = RouteParameter.Optional}
        );

        //FluentValidation
        FluentValidationModelValidatorProvider.Configure(config);    
    }
}

FluentValidation会自动将其错误插入到ModelState中.您应该包含错误消息.

public class ReadAllMenusByApplicationInputValidator : AbstractValidator<ReadAllMenusByApplicationInput> {
    public ReadAllMenusByApplicationInputValidator() {
        RuleFor(x => x.ApplicationName).NotEmpty()
            .WithMessage("The Application Name cannot be blank.");
    }
}

本文的一些内容超出了您的问题范围.主要包装响应,但其他一切应该适合你.

原文链接:https://www.f2er.com/csharp/99824.html

猜你在找的C#相关文章