Сериализация WebApi для Json с запросом POST - PullRequest
1 голос
/ 28 июня 2019

У меня есть следующий контроллер WebApi

[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. Сначала я просто хочу отправить запрос в службу, я попытался сделать это (используя этот пример ) через

[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 }

Q. Как я могу правильно сериализовать свой объект с помощью Newtonsoft.Json и отправить мне сервис?

1 Ответ

3 голосов
/ 28 июня 2019

Нет необходимости создавать HttpRequestMessage при использовании HttpClient.PostAsync.Просто создайте контент и отправьте его.

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);

Вы также можете явно указать действие для привязки к данным из тела запроса

//...
public async Task<IActionResult> RegisterFunction([FromBody]RegisterFunctionDto rsd) {
    //...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...