将ASP.NET Core OData与FluentValidation集成

时间:2020-04-06 08:27:34

标签: asp.net-core odata fluentvalidation

我正在尝试让OData使用FluentValidation验证我的模型。但是我似乎找不到告诉OData使用它的方法,因为它会给我这个响应

{
    "error": {
        "code": "",
        "message": "The input was not valid.",
        "details": [
            {
                "code": "",
                "message": "The input was not valid."
            }
        ]
    }
}

发送此有效载荷时

{
    "id": "",
    "name": "",
    "author": ""
}

控制器发布操作中的Blog参数也是null

我正在使用

  • netcoreapp3.1
  • Microsoft.AspNetCore.OData版本=“ 7.4.0-beta”
  • FluentValidation.AspNetCore版本=“ 9.0.0-preview3”

模型

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
}

验证器

public class BlogValidator : AbstractValidator<Blog> {
  public BlogValidator() {
    RuleFor(x => x.Id).NotEmpty();
    RuleFor(x => x.Name).NotEmpty();
    RuleFor(x => x.Author).NotEmpty();
  }
}

控制器

[Route("odata/[controller]s")]
public class BlogController : ODataController
{
    private readonly MyContext _context;

    public BlogController(MyContext context)
    {
        _context = context;
    }

    [HttpGet]
    [EnableQuery]
    public IActionResult Get() {...}

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] Blog blog) {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // omitted...
    }
}

启动

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MMContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));
        services.AddControllersWithViews().AddFluentValidation(options => options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()));

        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "../frontend/dist";
        });

        services.AddOData();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseRouting();

        var model = EdmModelBuilder.GetEdmModel();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.Select().Filter().OrderBy().Count().MaxTop(50);
            endpoints.MapODataRoute("odata", "odata", model);
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "..\\frontend";

            if (env.IsDevelopment())
            {
                spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
            }
        });
    }
}

0 个答案:

没有答案
相关问题