【问题标题】:API post not decting raw json modelAPI post 未检测到原始 json 模型
【发布时间】:2022-01-24 20:20:19
【问题描述】:

我再次尝试使用控制器的 post 方法,但该方法没有捕获 json 模型。休息,所有类型的标题都在工作,而不是 json post。

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

    public IConfiguration Configuration { get; }
    readonly string CorsPolicy = "MyPolicy";

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy(CorsPolicy, builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        services.AddControllersWithViews();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();
        app.UseCors(CorsPolicy);

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

谁能指导我应该改变什么? 或者我哪里错了?

【问题讨论】:

标签: c# json asp.net-core asp.net-web-api postman


【解决方案1】:

尝试匹配字段名称的大小写,并包含引号,例如"DepartmentId": 0

并且确认请求有Content-Type: application/json

【讨论】:

  • 不...仍然无法正常工作
【解决方案2】:

由于您使用的是 json ,因此您必须将 [FromBody] 添加到操作中

pubic ActionResult Post([FromBody] department)

同时修复邮递员中的 json

{
    "DepartmentId": 0,
    "DepartmentName": "bpu"
}

还支持无敏感字母大小写,将这些选项添加到启动

using Newtonsoft.Json.Serialization;
.....

services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());

【讨论】:

  • 不客气!请不要忘记接受答案。您可以通过单击我的答案旁边的复选标记来完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多