Home > Mobile >  API post not decting raw json model
API post not decting raw json model

Time:12-24

once again, I'm trying to hit post method of controller but the method is not catching json model. rest, all types of headers are working instead of json post.

enter image description here

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

    public IConfiguration Configuration { get; }
    readonly string CorsPolicy = "MyPolicy";

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy(CorsPolicy, builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        services.AddControllersWithViews();

    }

    // 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("/Home/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();

        app.UseRouting();
        app.UseCors(CorsPolicy);

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

enter image description here

Can anyone please guide me on what should I need to change? or where am I wrong in this?

CodePudding user response:

Try matching case of field name, and include quotes, e.g. "DepartmentId": 0

And confirm request has Content-Type: application/json

CodePudding user response:

since you are using json , you have to add [FromBody] to the action

pubic ActionResult Post([FromBody] department)

also fix json in postman

{
    "DepartmentId": 0,
    "DepartmentName": "bpu"
}

also to support no sensitive letter case add these options to startup

using Newtonsoft.Json.Serialization;
.....

services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());
  • Related