【问题标题】:HttpPost with JSON parameter is not working in ASP.NET Core 3带有 JSON 参数的 HttpPost 在 ASP.NET Core 3 中不起作用
【发布时间】:2020-02-18 05:30:20
【问题描述】:

因此,我将我的 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,那个

默认情况下,当您在 Startup.cs 中调用 AddMvc() 时,会自动配置 JSON 格式化程序 JsonInputFormatter,但您可以根据需要添加其他格式化程序,例如将 XML 绑定到对象。

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

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" }

更新

邮递员标头: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");
            });
        });
        //
    }

应用程序.cs

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

【问题讨论】:

  • 1.你得到什么状态码? 2. 你是如何发送有效载荷的?还请包含 javascript 代码。
  • 它是一个 API。我没有使用javascript。我在调试时评论了大部分内容 - 附上图片。
  • 实际上,我使用您的代码创建了一个新的v3.0.100 项目,但是您的有效负载对我来说很好。我怀疑您未在此处显示的代码中是否有问题。您是否配置了自定义服务/模型绑定器/过滤器?
  • 我在 postman 的更新部分添加了更多代码。我还创建了另一个应用程序,只是在那里复制了这个 httppost 函数和 application.cs,评论了其他所有内容,但它没有工作:S...
  • 您是否尝试在启动时添加 json 序列化内容?还有另一种发送 json 对象的方法,例如使用蛇案例类型的序列化

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


【解决方案1】:

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

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

公开课申请 { 公共字符串 AppName {get;set;} 公共字符串 licenseKey {get;set;} }

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2021-08-27
    • 2020-02-10
    • 2019-08-15
    相关资源
    最近更新 更多