我有一个Web API服务调用,用于更新用户的首选项.不幸的是,当我从jQuery ajax调用调用此POST方法时,请求参数对象的属性始终为null(或默认值),而不是传入的内容.如果我使用REST客户端调用相同的方法(我使用Postman) ,它工作得很漂亮.我无法弄清楚我做错了什么,但希望有人见过这个.这很简单......
这是我的请求对象:
public class PreferenceRequest
{
[Required]
public int UserId;
public bool usePopups;
public bool useTheme;
public int recentCount;
public string[] detailsSections;
}
Run Code Online (Sandbox Code Playgroud)
这是UserController类中的控制器方法:
public HttpResponseMessage Post([FromBody]PreferenceRequest request)
{
if (request.systemsUserId > 0)
{
TheRepository.UpdateUserPreferences(request.UserId, request.usePopups, request.useTheme,
request.recentCount, request.detailsSections);
return Request.CreateResponse(HttpStatusCode.OK, "Preferences Updated");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "You must provide User ID");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的ajax电话:
var request = {
UserId: userId,
usePopups: usePopups,
useTheme: useTheme,
recentCount: recentCount,
detailsSections: details
};
$.ajax({
type: "POST",
data: request,
url: …Run Code Online (Sandbox Code Playgroud) 我想从Web API(Asp.net Core 2.1)中仅返回标准化的错误响应,但我似乎无法弄清楚如何处理模型绑定错误.
该项目只是从"ASP.NET Core Web Application">"API"模板创建的.我有一个简单的动作定义为:
[Route("[controller]")]
[ApiController]
public class MyTestController : ControllerBase
{
[HttpGet("{id}")]
public ActionResult<TestModel> Get(Guid id)
{
return new TestModel() { Greeting = "Hello World!" };
}
}
public class TestModel
{
public string Greeting { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如果我使用无效的Guid(例如https://localhost:44303/MyTest/asdf)向此操作发出请求,我会收到以下响应:
{
"id": [
"The value 'asdf' is not valid."
]
}
Run Code Online (Sandbox Code Playgroud)
我有以下代码Startup.Configure:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
JsonErrorMiddleware.CreateSingleton(env);
if (!env.IsDevelopment())
{
app.UseHsts();
}
app
.UseHttpsRedirection()
.UseStatusCodePages(async ctx => …Run Code Online (Sandbox Code Playgroud)