Deivyyyy
Deivyyyy

Reputation: 27

Controller accepts data case sensitively from application/json payload

I'm writing a WebApi with OData and I've encountered a problem. The problem is that controllers accept data only case sensitively. For instance, when I pass {"name":"London"}, it gives a null object and an error The property 'name' does not exist on type 'Taxes.Service.DataLayer.Models.Municipality'. Make sure to only use property names that are defined by the type.. But when I pass {"Name":"London"}, everything is OK - the object is created and value is set. Don't actually know what may be wrong. Thanks.

BaseController.cs

public class BaseController<T> : ODataController where T : BaseModel
{
    protected readonly TaxesContext Context;

    public BaseController(TaxesContext context)
    {
        Context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody]T baseObject)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState
                .SelectMany(x => x.Value.Errors, (y, z) => z.Exception.Message);

            return BadRequest(errors);
        }

        await Context.Set<T>().AddAsync(baseObject);
        await Context.SaveChangesAsync();
        return Created(baseObject);
    }
}

BaseModel.cs

public class BaseModel
{
    public int Id { get; set; }
}

Municipality.cs

public class Municipality : BaseModel
{
    public string Name { get; set; }
    public ICollection<Tax> Taxes { get; set; }
}

Tax.cs

public class Tax : BaseModel
{
    [Required]
    public int MunicipalityId { get; set; }

    [Required]
    public virtual Municipality Municipality { get; set; }

    [Required]
    public virtual TaxFrequency Frequency { get; set; }

    [Required]
    public virtual DateTime StartDate { get; set; }

    [Required]
    public virtual DateTime EndDate { get; set; }

    [Required]
    public virtual double Value { get; set; }
}

Startup.cs

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.AddOData();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddDbContext<TaxesContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc(routes =>
        {
            routes.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
            routes.MapODataServiceRoute("odata", "odata", GetEdmModel());
            routes.MapRoute("Default", "{controller}/{action=Index}/{id?}");
        });
    }

    private static IEdmModel GetEdmModel ()
    {
        var builder = new ODataConventionModelBuilder();

        builder.EntitySet<DataLayer.Models.Municipality>("Municipalities");
        builder.EntitySet<DataLayer.Models.Tax>("Taxes");

        var function = builder.Function("MunicipalityWithTax");
        function.ReturnsCollectionViaEntitySetPath<DataLayer.Models.Municipality>("Municipalities");

        return builder.GetEdmModel();
    }
}

Postman request enter image description here

Upvotes: 0

Views: 408

Answers (1)

egnomerator
egnomerator

Reputation: 1115

Add camelCase support with this statement: builder.EnableLowerCamelCase()

private static IEdmModel GetEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EnableLowerCamelCase();                   // <-- add this line
        ...

source

Upvotes: 1

Related Questions