小编May*_*ayo的帖子

继续断言

断言后有什么方法可以继续测试吗?..我需要查看断言导致的所有情况.

foreach (var ex in data)
{
     Assert.AreEqual(ex1, ex, msg);
}
Run Code Online (Sandbox Code Playgroud)

c# unit-testing

4
推荐指数
1
解决办法
6586
查看次数

Asp Core 3 - 如何在控制器方法中允许可为空的 [FromBody] 对象

假设我有一个带有一个 POST 方法的简单控制器,该方法从其主体中接受一个对象。但是,此对象在 HTTP 请求正文中的存在应该是可选的。我尝试使用以下代码实现此行为

public class User
{
    public string Name { get; set; }
}

[ApiController]
[Route("[controller]")]
public class GreetingController : ControllerBase
{
    [HttpPost]
    public string SayHello([FromBody] User user = null)
    {
        return "Hello " + user?.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用主体中的对象发出请求,则一切正常。但是使用这种配置,它无法发出空体的 POST 请求。如果我创建一个没有Content-Type标头的请求(因为实际上没有内容),我会收到以下错误:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "|192e45d5-4bc216316f8d3966."
}
Run Code Online (Sandbox Code Playgroud)

如果Content-Type标头具有值,application/json则响应如下所示:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|192e45d6-4bc216316f8d3966.",
    "errors": {
        "": …
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core asp.net-core-3.1

3
推荐指数
2
解决办法
1516
查看次数