HttpPost with JSON parameter is not working in ASP.NET Core 3

1.9k views Asked by At

So, I migrated my RestAPI project to ASP.NET Core 3.0 from ASP.NET Core 2.1 and the HttpPost function that previously worked stopped working.

    [AllowAnonymous]
    [HttpPost]
    public IActionResult Login([FromBody]Application login)
    {
        _logger.LogInfo("Starting Login Process...");

        IActionResult response = Unauthorized();
        var user = AuthenticateUser(login);

        if (user != null)
        {
            _logger.LogInfo("User is Authenticated");
            var tokenString = GenerateJSONWebToken(user);

            _logger.LogInfo("Adding token to cache");
            AddToCache(login.AppName, tokenString);                

            response = Ok(new { token = tokenString });

            _logger.LogInfo("Response received successfully");
        }

        return response;
    }

Now, the login object has null values for each property. I read here, that

By default, when you call AddMvc() in Startup.cs, a JSON formatter, JsonInputFormatter, is automatically configured, but you can add additional formatters if you need to, for example to bind XML to an object.

Since AddMvc was removed in aspnetcore 3.0, now I feel this is why I am unable to get my JSON object anymore. My Startup class Configure function looks like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseRouting();
        //app.UseAuthorization();
        //app.UseMvc(options
        //    /*routes => {
        //    routes.MapRoute("default", "{controller=Values}/{action}/{id?}");
        //}*/);
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapRazorPages();
        });
    }

Debugging the logging object

The request I am sending through postman (raw and JSON options are selected)

{ "AppName":"XAMS", "licenseKey": "XAMSLicenseKey" }

UPDATES

Postman Header: Content-Type:application/json

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {            
        //_logger.LogInformation("Starting Log..."); //shows in output window

        services.AddSingleton<ILoggerManager, LoggerManager>();

        services.AddMemoryCache();
        services.AddDbContext<GEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        services.AddControllers();
        services.AddRazorPages();

        //Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = "https://localhost:44387/";
            options.Audience = "JWT:Issuer";
            options.TokenValidationParameters.ValidateLifetime = true;
            options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(5);
            options.RequireHttpsMetadata = false;
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("GuidelineReader", p => {
                p.RequireClaim("[url]", "GuidelineReader");
            });
        });
        //
    }

Application.cs

 public class Application
 {
    public string AppName;
    public string licenseKey;
 }
1

There are 1 answers

0
itminus On BEST ANSWER

With you updated code, I think the reason is you didn't create setter for your properties.

To fix the issue, change your Application model as below:

public class Application
{
    public string AppName  {get;set;}
    public string licenseKey  {get;set;}
}