Возвращает строку (для подробностей успеха или исключения) с PostJsonAsyn c -. NET Core REST API - PullRequest
0 голосов
/ 18 марта 2020

Я хочу, чтобы мой REST API возвращал клиенту строку с подробной информацией об исключении. Мой код на стороне клиента:

public async Task CreateUnit(UnitEntity unit)
    {
        try
        {
            var response = await _http.PostJsonAsync<HttpResponseMessage>("api/units", unit);
        }

        catch(Exception e)
        {
            //todo want to display error from the service and carry on
            //throw;
        }
    }

А код для службы / API:

[HttpPost]
    public HttpResponseMessage CreateUnit(UnitEntity unit)
    {
        try
        {
            Dal.CreateUnit(unit);
            HttpResponseMessage response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.Created;
            response.Content = new StringContent($"The unit {unit.UnitName} was created successfully");
            return response;

        }
        catch(Exception e)
        {
            //todo send error message in Http response if possible
            //throw;
            return new HttpResponseMessage() {StatusCode = HttpStatusCode.NotAcceptable, Content = new StringContent(e.Message)};
        }
    }

Я попытался просто вернуть строку, и она в основном говорит, что * Сериализатор 1009 * не может десериализовать его (потому что это уже необработанная строка, а не JSON). Код выше выдает исключение:

Deserialization of reference types without parameterless constructor is not supported. Type 'System.Net.Http.HttpContent'
...