带有 JSON 参数的 HttpPost 在 ASP.NET Core 3 中不起作用

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

所以,我将我的 RestAPI 项目从 ASP.NET Core 2.1 迁移到 ASP.NET Core 3.0,之前工作的 HttpPost 功能停止工作。

    [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;
    }

现在,登录 object 每个 属性 都有空值。我读 here

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.

自从在 aspnetcore 3.0 中删除了 AddMvc,现在我觉得这就是我无法再获得 JSON object 的原因。我的启动 class 配置函数如下所示:

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();
        });
    }

我通过邮递员发送的请求(选择了原始和 JSON 选项)

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

更新

邮递员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;
 }

随着您更新代码,我认为原因是您没有为您的属性创建 setter

要解决此问题,请如下更改您的 Application 模型:

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