【问题标题】:Post request values always null after upgrading to .Net Core 3.0升级到 .Net Core 3.0 后,发布请求值始终为空
【发布时间】:2020-04-04 08:57:49
【问题描述】:

我已经尝试了所有找到的解决方案,但大多数都不适用于我的问题。我正在使用 JSON 发送帖子请求,并且在 3.0 之前它们都可以正常工作。
您可以在我的控制器中看到我有 [FromBody] 并且我的模型具有属性。这是我从其他人那里看到的两个问题。您还可以看到我的请求值与我的模型名称匹配,并且没有丢失。我找不到其他可能导致此问题的原因。

编辑 - 根据下面的评论,我检查了 Json 规则。最初的默认规则是使值名称的第一个字符小写。它在下降的过程中会这样做,但我不知道在向服务器发送值时如何判断这是否会影响它。是否可以在某处放置断点以在将帖子值发送到控制器之前查看它们?

编辑2 - 将启动更改为此使其模型不为空,但所有值都是默认值。字符串为空,整数为 0。

services.AddControllers().AddJsonOptions(o =>
            {
                o.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
            });

看起来大多数与名称更改有关的 json 选项不会影响我所看到的反序列化。

Startup.cs

   public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers();


            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            //services.AddMvc();

            services.AddTransient<AuthService>();
            services.AddTransient<LocationService>();
            services.AddTransient<MessageService>();
            services.AddTransient<AutoAssignService>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseAuthentication();

            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthorization();


            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
        }
    }

请求模型

public class CensusManagementSearch
{
    public int LocationId { get; set; }
    public int PracticeId { get; set; }
    public string Name { get; set; }
    public int StatusId { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public bool Print { get; set; }
}

我的控制器方法

[HttpPost]
public IActionResult PostCensusManagement([FromBody] CensusManagementSearch search)
{
}

这是我在请求中发送的数据

【问题讨论】:

  • the issue:这些信息并没有真正的帮助。它没有说明究竟是什么不起作用,即您是否在任何地方收到任何错误消息,您是否尝试调试问题以确保它确实完成了预期的事情。
  • 也许它与this change相关?
  • @John_ReinstateMonica 我倾向于这样的事情。我会检查这些。如果它们有效,我会通知您,您可以将其作为答案。
  • 是的,我可能就是这样做的。您可能需要阅读正文,然后将其倒回。 This might help
  • 如果将有效负载绑定到模型时出现某种错误,您可以在 ModelState 属性上看到它。 ModelState.IsValid 是否等于 false

标签: c# json asp.net-core .net-core asp.net-core-mvc


【解决方案1】:

通常,当 JSON 有效负载无法绑定到控制器操作的模型时,您会看到 ModelState.IsValid 等于 false。在调试和向下钻取时展开 ModelState.Values 属性将为您提供有关 JSON 解析期间失败的详细错误。

请记住,ASP.NET Core 3.0 使用新的原生 JSON 引擎而不是 JSON.NET,后者的限制要大得多。这可能是某些属性/类型现在无法正确解析的原因。

要使用自定义日期格式,您必须实现自己的转换器:

public class DateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.ParseExact(reader.GetString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));
    }
}


// In ConfigureServices() of Startup.cs

services.AddControllers()
        .AddJsonOptions(options =>
         {
             options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
         });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2020-03-20
    相关资源
    最近更新 更多