【发布时间】: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