3

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;
 }
Samra
  • 1,815
  • 4
  • 35
  • 71
  • 1. What's status code did you get ? 2. How did you send the payload? Please also include the javascript code. – itminus Oct 22 '19 at 07:35
  • Its an API. I didnot use javascript. I have commented most things while debugging - attached the image. – Samra Oct 22 '19 at 22:48
  • Actually, I create a new `v3.0.100` project using your code, but your payload works fine for me. I suspect whether there's something wrong within the code that you didn't show here. Did you configure a custom service / model binder/ filter? – itminus Oct 23 '19 at 01:18
  • I have put in more code in postman under updates section. I also created another application just copied this httppost function there and application.cs, commented everything else and it didnot work :S... – Samra Oct 23 '19 at 04:35
  • Did you try adding json serializing stuff on your startup there is another way to send json object like serialization using snake case kind – Eliotjse Oct 23 '19 at 04:51

1 Answers1

3

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;}
}
itminus
  • 23,772
  • 2
  • 53
  • 88