首页 > 解决方案 > Aspnet Core 3 ajax 调用参数为空

问题描述

当我进行 Ajax 调用时,我的所有参数始终为空。

这是我的JavaScript ...

var data = {
    username: "john",
    password: "123"
};

$.ajax({
    type: "POST",
    url: "/MyCallback",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) { alert(data); },
    failure: function (errMsg) { alert(errMsg); }
});

这是我的控制器...

public class UserModel
{
    string username { get; set; }
    string password { get; set; }
}


[Route("MyCallback")]
[HttpPost]
public JsonResult MyCallback([FromBody] UserModel query)
{
    // query.username and query.password is null
    return Json(true);
}

而我的创业...

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

    services.AddControllersWithViews().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });

    services.AddRazorPages(options =>
    {
        options.RootDirectory = "/Features";
    });

    services.Configure<RazorViewEngineOptions>(options =>
    {
        options.ViewLocationExpanders.Add(new FeatureFolderViewLocationExpander());
    });

    services.AddCors();

    services.AddHttpContextAccessor();
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "Features")
        ),
        RequestPath = "/Features"
    });

    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

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

知道为什么我的参数总是为空吗?

标签: asp.net-core

解决方案


您的模型中的属性是 private ,您应该将其更改为 public ,否则您无法使用此属性。

 public class UserModel
 {
     public string username { get; set; }
     public string password { get; set; }
 }

推荐阅读