canton7 / RestEase

Easy-to-use typesafe REST API client library for .NET Standard 1.1 and .NET Framework 4.5 and higher, which is simple and customisable. Inspired by Refit
MIT License
1.08k stars 109 forks source link

adding Content-Type header issue #167

Closed abdeldjalil-fellah closed 3 years ago

abdeldjalil-fellah commented 4 years ago
[Header("Content-Type", "application/json; charset=UTF-8")]
public interface IApiPrivilege 
{
    [Get("/shuffle")]
    Task<Message<privilege>> ShuffleSync([Body] privilege model, string query); 
}

var httpClient = new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator });
httpClient.BaseAddress = new Uri("http://localhost:5000");

var api = RestClient.For<IApiPrivilege>(httpClient);

requests sent to the server do not contain the "Content-Type" header! hence api.ShuffleSync(model, query) generates 415 status code how to add that header globally to the httpClient instead of adding it to each interface?

canton7 commented 4 years ago

That should be working. Using this sample:

public class Program
{
    static void Main()
    {
        var httpClient = new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator });
        httpClient.BaseAddress = new Uri("https://en62ab5snoazt.x.pipedream.net");

        var api = RestClient.For<IApiPrivilege>(httpClient);
        api.ShuffleSync("test").Wait();
    }

    [Header("Content-Type", "application/json; charset=UTF-8")]
    public interface IApiPrivilege
    {
        [Get("/shuffle")]
        Task ShuffleSync([Body] string foo);
    }
}

Produces this request, and you can see the Content-Type header there.

I don't believe HttpClient has a way for you to set a default content header.

abdeldjalil-fellah commented 4 years ago

after debugging actually the error was thrown when model == null, so it has nothing with RestEase! and there is no need to add the [Header] attribute, I think RestEase added it automatically if any [Body] attribute is detected.

canton7 commented 4 years ago

Content-related headers only get applied when there's actually a content -- if the body is null, Content-Type won't be sent.

canton7 commented 3 years ago

This has been changed in version 1.5.1 -- if a [Body] parameter is declared on the method, then content-related headers are always sent.