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

标签 json asp.net-core http-post asp.net-core-webapi inputformatter

因此,我将我的 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;
    }

现在,登录对象的每个属性都有空值。我读了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 对象的原因。我的 Startup 类 Configure 函数如下所示:

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

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

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

更新

postman 标题:Content-Type:application/json

启动.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");
            });
        });
        //
    }

应用程序.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;}
}

关于json - 带有 JSON 参数的 HttpPost 在 ASP.NET Core 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497924/

相关文章:

java - 放心 - 如何放心地解析数组元素

json - Xidel json xpath - 如何获取多个元素的值

PHP MySQL 选择并回显为 json

c# - 如何在 MVC 中将 URL 作为查询字符串参数传递

java - 在 doPost() 响应中发送数据?

php - JSON 字符串到 PHP JSON 数组

c# - ASP.NET Core MVC 通配符路由无法使用与另一个正在工作的设置相同的设置

c# - 如何在 dev .net 6 上的项目中检索环境变量

php - Objective-C->JSON->PHP 数组

http - 在 RESTfull 场景中,哪些 Action 被认为是幂等的?