C# HttpClient Serialize/Deserialize new

Viewed 34

I am writing a basis class to simplify REST API calls. I am now at the point to decide how to handle the requests and responses from the perspective of the Serialize/Deserialize objects.

Below is a POST request example. Basically it receives the path and handle the response using as JToken.Parse.

Example

public async Task<Uri> PostCreateAsync(string entitySetName, object body)
{
    try
    {
        using (var message = new HttpRequestMessage(HttpMethod.Post, entitySetName))
        {
            message.Content = new StringContent(SystemTextJson.SerializeToString(body));
            message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            using (HttpResponseMessage response = await SendAsync(message))
            {
                return new Uri(response.Headers.GetValues("OData-EntityId").First());
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Usage

public interface IRecord
{
    Guid Id { get; set; }
    string Name { get; set; }
}

public class Contact : IRecord
{
    public Guid Id { get; set; } = Guid.Empty;
    public string FullName { get; set; } = null!;
    public string LastName { get; set; } = null!;
    public string JobTitle { get; set; } = null!;
}

var contact = new Contact()
{
    LastName = "Gil",
    JobTitle = "Developer",
    FullName = "Andre Gil"
};

var response = await _api.PostCreateAsync("contacts", contact);

First problem here. How to provide the api name "contacts" generic? Json decoration?

Second, the Id attribute cannot be sent through on POST operation. Of course, I could use JsonIgnore. But the "Id" must be sent through in case of PATCH or PUT.

0 Answers
Related