asp.net-core - 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();
});
}
知道为什么我的参数总是为空吗?
解决方案
您的模型中的属性是 private ,您应该将其更改为 public ,否则您无法使用此属性。
public class UserModel
{
public string username { get; set; }
public string password { get; set; }
}
推荐阅读
- symfony - Sonata Admin Bundle:按计数一对多关系排序
- python - MatPlotLib 在图例中从 df 创建标签
- postgresql - 单字符文本搜索替代
- laravel - 如何将 CSRF 令牌安全地传递到单独的 VueJS 前端?
- tensorboard - 如何在张量板中制作表格
- ruby-on-rails - Ruby on Rails Grape API 省略属性
- android - 数据显示为空,但 url 适用于 Postman
- php - OPENCART php 创建了新的控制器查询方法并查看获取空行
- windows - 命令提示符 - 使用批处理文件上传文件时出现“找不到文件”错误
- javascript - Three.js 粒子和滚动处理