【发布时间】:2019-10-06 16:39:31
【问题描述】:
我正在使用 Postman 和 Insomnia 向我的 .NET CORE 应用程序发送 POST 请求,我在 [HttpPost] 方法中的断点被命中,但正文为空,并且在调试 Visual Studio 时显示该请求是 GET请求。
我的 StartupClass:
namespace MyBuildingRestfulWebWithCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//services.AddMvc();
services.AddControllers();
services.AddSingleton<IProductService, ProductService>();
services.AddDbContext<FlixOneStoreContext>(options => options.UseSqlServer("myconnectionstring;"));
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}
}
}
我的控制器:
namespace MyBuildingRestfulWebWithCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
private readonly FlixOneStoreContext _context;
public CustomersController(FlixOneStoreContext context)
{
_context = context;
}
[HttpGet] //this one works
public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
{
return await _context.Customers.ToListAsync();
}
[HttpPost("test")] //this one fails because customers variable is null
public async Task<ActionResult<Customer>> PostCustomers([FromBody] Customer customers)
{
if (_context.Customers.Any(customer => customer.Email == customers.Email))
{
return StatusCode((int)HttpStatusCode.Conflict, "Email already in use");
}
_context.Customers.Add(customers);
//...
return CreatedAtAction("GetCustomers", new { id = customers.Id }, customers);
}
[HttpPost("test2")] //this one fails because request.Content is null,
//but Visual Studio debugger shows me that the request.Method is a GET request
public async Task<ActionResult<string>> PostCustomers(HttpRequestMessage request)
{
string body = await request.Content.ReadAsStringAsync();
return body;
}
}
我正在使用 .NET Core 3.0.0,并通过 Postman 和 Insomnia 发送我的请求以确认错误不在客户端 - 我已将 Postman 中的正文设置为原始 -JSON,并将 Insomnia 中的正文设置为 JSON(和我的 JSON 验证)
我的请求正文如下:
{
"id":1,
"gender": "M",
"email":"test@test.com",
"firstname": "Firstname",
"lastname": "LastName",
"dob":"1970-07-05T00:00:0",
"mainaddressid":"mainaddr",
"fax":"fax",
"password": "pw",
"newsletteropted": false
}
我已阅读官方文档中关于如何迁移到 .NET Core 3 的 this 文章,但没有发现任何帮助。
有什么想法吗?我是否错误地配置了我的启动类,或者使用了错误的某些属性? (我对 .NET Core 不太熟悉……)
【问题讨论】:
-
我认为
HttpRequestMessage在 aspnet 核心中不受支持。仅在经典 webapi 中。你应该改用this.HttpContext.Request.Body -
您正在使用带有 true 的 SuppressModelStateInvalidFilter 来抑制 ModelState 错误;因此,如果您的有效负载对象格式错误,则使用 null 调用 post 请求,而不是抛出 http 错误请求(400)。尝试使用 SuppressModelStateInvalidFilter 的错误值。如果你得到 400 则更正有效载荷。另外,能否请您发布客户类的类型定义?
-
正如migration doc 中所说,您必须使用包
Microsoft.AspNetCore.Mvc.WebApiCompatShim来添加对HttpRequestMessage参数的支持。