json - 使用 POST 请求将 WebApi 序列化为 Json

标签 json asp.net-core serialization swagger

我有以下 WebApi Controller

[Route("api/[controller]")]
public class FunctionController : ControllerBase
{
    private readonly ILogger<FunctionController> _logger;
    private readonly IServiceAccessor<IFunctionManagementService> _functionManagementService;

    public FunctionController(
        IServiceAccessor<IFunctionManagementService> FunctionManagementService,
        ILogger<FunctionController> logger)
    {
        _functionManagementService = FunctionManagementService;
        _logger = logger;
    }

    [HttpPost]
    [SwaggerOperation(nameof(RegisterFunction))]
    [SwaggerResponse(StatusCodes.Status200OK, "OK", typeof(FunctionRegisteredResponseDto))]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Bad Request")]
    public async Task<IActionResult> RegisterFunction(RegisterFunctionDto rsd)
    {
        var registeredResponse = await _functionManagementService.Service.RegisterFunctionAsync(rsd);
        if (registeredResponse.Id > -1)
            return Ok(registeredResponse);

        return BadRequest(registeredResponse);
    }

    [HttpDelete("{id}")]
    [SwaggerOperation(nameof(UnregisterFunction))]
    [SwaggerResponse(StatusCodes.Status200OK, "OK")]
    [SwaggerResponse(StatusCodes.Status404NotFound, "Not Found")]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Bad Request")]
    public async Task<IActionResult> UnregisterFunction(string sid)
    {
        if (!long.TryParse(sid, out long id))
            return new BadRequestObjectResult(new { message = "400 Bad Request", UnknownId = sid });

        if (!await _functionManagementService.Service.UnregisterFunctionAsync(id))
            return new NotFoundObjectResult(new { message = "404 Not Found", UnknownId = sid });

        return new OkObjectResult(new { Message = "200 OK", Id = id, Unregistered = true });
    }
}

我正在尝试使用 MSTest 测试对此服务的请求。首先,我只想向服务发送请求,我尝试通过

执行此操作(使用 this example )
[TestMethod]
public async Task BuildObjectFromValidResponse()
{
    RegisterFunctionDto rsd = Utils.GetRegisterFunctionDtoObject();
    string serializedDto = JsonConvert.SerializeObject(rsd);

    var inputMessage = new HttpRequestMessage()
    {
        Content = new StringContent(serializedDto, Encoding.UTF8, "application/json")
    };
    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.PostAsync("api/Function", inputMessage.Content);

    // Also tried this.
    //HttpResponseMessage response = await client.PostAsJsonAsync("api/Function", JsonConvert.SerializeObject(rsd));
}

public class RegisterFunctionDto
{
    public string Name { get; set; }
    public decimal Movement { get; set; }
    public int Quantity { get; set; }
}

public static class Utils
{
    private static Random random = new Random();

    public static string GetName(int length = 5)
    {
        StringBuilder resultStringBuilder = new StringBuilder();
        string dictionaryString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int i = 0; i < length; i++)
            resultStringBuilder.Append(dictionaryString[random.Next(dictionaryString.Length)]);

        return resultStringBuilder.ToString();
    }

    public static RegisterFunctionDto GetRegisterFunctionDtoObject()
    {
        return new RegisterFunctionDto()
        {
            Name = GetName(),
            Instruction = random.Next() % 2 == 0 ? BuySell.Buy : BuySell.Sell,
            PriceMovement = Convert.ToDecimal(random.NextDouble()),
            Quantity = 100
        };
    }
}

但是当我将其发布到服务时,收到的对象是默认对象,这是一个具有所有默认值的对象。所以在 RegisterFunction 中我收到了

rsd { Name = "", Movement = 0.0, Quantity = 0 }

问。如何使用 Newtonsoft.Json 正确序列化我的对象并将其发布到我的服务?

最佳答案

如果使用HttpClient.PostAsync,则无需创建HttpRequestMessage。只需构建内容并发送即可。

RegisterFunctionDto rsd = Utils.GetRegisterFunctionDtoObject();
string serializedDto = JsonConvert.SerializeObject(rsd);
var content = new StringContent(serializedDto, Encoding.UTF8, "application/json");    

HttpResponseMessage response = await client.PostAsync("api/Function", content);

您还可以明确告诉操作绑定(bind)到请求正文中的数据

//...
public async Task<IActionResult> RegisterFunction([FromBody]RegisterFunctionDto rsd) {
    //...
}

关于json - 使用 POST 请求将 WebApi 序列化为 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56806658/

相关文章:

json - 创建JSON字符串,PowerShell对象

json - Dockerrun.aws.json 版本无效,中止部署

c# - dotnet 工具 aspnet-codegenerator 在错误的路径中查找可执行文件

c# - Dot Net Core 2.0 多重cookie

c# - 二进制对象图序列化

c++ - boost 动态数组的序列化

javascript - 带有嵌套 JSON 的 JSON.parse()

json - Play Framework 2.4 Writes[-A] vs OWrites[-A],Format[A] vs OFormat[A]。目的?

mongodb - 无法连接到 Dockerized MongoDb 服务器 - 绑定(bind) ip - 没有机会授权

python - 如何插入反序列化的 Django 对象?