Интеграция ASP. NET Core OData с FluentValidation - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь заставить 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 Version = "7.4. 0-бета "
  • FluentValidation.AspNetCore Version =" 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");
            }
        });
    }
}
...