8000 Isolated Content Serialization by stevewgh · Pull Request #571 · reactiveui/refit · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Isolated Content Serialization #571

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Dec 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 52 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ type of the parameter:
* If the type is `string`, the string will be used directly as the content
* If the parameter has the attribute `[Body(BodySerializationMethod.UrlEncoded)]`,
the content will be URL-encoded (see [form posts](#form-posts) below)
* For all other types, the object will be serialized as JSON.
* For all other types, the object will be serialized using the content serializer specified in
RefitSettings (JSON is the default).

#### Buffering and the `Content-Length` header

Expand Down Expand Up @@ -198,17 +199,19 @@ APIs:
```csharp
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com",
new RefitSettings {
JsonSerializerSettings = new JsonSerializerSettings {
ContractResolver = new SnakeCasePropertyNamesContractResolver()
ContentSerializer = new JsonContentSerializer(
new JsonSerializerSettings {
ContractResolver = new SnakeCasePropertyNamesContractResolver()
}
});
)});

var otherApi = RestService.For<IOtherApi>("https://api.example.com",
new RefitSettings {
JsonSerializerSettings = new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver()
ContentSerializer = new JsonContentSerializer(
new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
});
)});
```

Property serialization/deserialization can be customised using Json.NET's
Expand All @@ -223,6 +226,48 @@ public class Foo
}
```

#### XML Content

XML requests and responses are serialized/deserialized using _System.Xml.Serialization.XmlSerializer_.
By default, Refit will use JSON content serialization, to use XML content configure the ContentSerializer to use the `XmlContentSerializer`:

```csharp
var gitHubApi = RestService.For<IXmlApi>("https://www.w3.org/XML",
new RefitSettings {
ContentSerializer = new XmlContentSerializer()
});
```

Property serialization/deserialization can be customised using attributes found in the _System.Xml.Serialization_ namespace:

```csharp
public class Foo
{
[XmlElement(Namespace = "https://www.w3.org/XML")]
public string Bar { get; set; }
}
```

The _System.Xml.Serialization.XmlSerializer_ provides many options for serializing, those options can be set by providing an `XmlContentSerializerSettings` to the `XmlContentSerializer` constructor:

```csharp
var gitHubApi = RestService.For<IXmlApi>("https://www.w3.org/XML",
new RefitSettings {
ContentSerializer = new XmlContentSerializer(
new XmlContentSerializerSettings
{
XmlReaderWriterSettings = new XmlReaderWriterSettings()
{
ReaderSettings = new XmlReaderSettings
{
IgnoreWhitespace = true
}
}
}
)
});
```

#### <a name="form-posts"></a>Form posts

For APIs that take form posts (i.e. serialized as `application/x-www-form-urlencoded`),
Expand Down
53 changes: 34 additions & 19 deletions Refit.Tests/MultipartTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -402,9 +402,16 @@ public async Task MultipartUploadShouldWorkWithFileInfoPart()
}
}

[Fact]
public async Task MultipartUploadShouldWorkWithAnObject()
[Theory]
[InlineData(typeof(JsonContentSerializer), "application/json")]
[InlineData(typeof(XmlContentSerializer), "application/xml")]
public async Task MultipartUploadShouldWorkWithAnObject(Type contentSerializerType, string mediaType)
{
if (!(Activator.CreateInstance(contentSerializerType) is IContentSerializer serializer))
{
throw new ArithmeticException($"{contentSerializerType.FullName} does not implement {nameof(IContentSerializer)}");
}

var model1 = new ModelObject
{
Property1 = "M1.prop1",
Expand All @@ -421,25 +428,33 @@ public async Task MultipartUploadShouldWorkWithAnObject()

Assert.Equal("theObject", parts[0].Headers.ContentDisposition.Name);
Assert.Null(parts[0].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[0].Headers.ContentType.MediaType);
var result0 = JsonConvert.DeserializeObject<ModelObject>(await parts[0].ReadAsStringAsync());
Assert.Equal(mediaType, parts[0].Headers.ContentType.MediaType);
var result0 = await serializer.DeserializeAsync<ModelObject>(parts[0]).ConfigureAwait(false);
Assert.Equal(model1.Property1, result0.Property1);
Assert.Equal(model1.Property2, result0.Property2);
}
};

var settings = new RefitSettings()
{
HttpMessageHandlerFactory = () => handler
HttpMessageHandlerFactory = () => handler,
ContentSerializer = serializer
};

var fixture = RestService.For<IRunscopeApi>(BaseAddress, settings);
var result = await fixture.UploadJsonObject(model1);
}

[Fact]
public async Task MultipartUploadShouldWorkWithObjects()
[Theory]
[InlineData(typeof(JsonContentSerializer), "application/json")]
[InlineData(typeof(XmlContentSerializer), "application/xml")]
public async Task MultipartUploadShouldWorkWithObjects(Type contentSerializerType, string mediaType)
{
if (!(Activator.CreateInstance(contentSerializerType) is IContentSerializer serializer))
{
throw new ArithmeticException($"{contentSerializerType.FullName} does not implement {nameof(IContentSerializer)}");
}

var model1 = new ModelObject
{
Property1 = "M1.prop1",
Expand All @@ -451,7 +466,6 @@ public async Task MultipartUploadShouldWorkWithObjects()
Property1 = "M2.prop1"
};


var handler = new MockHttpMessageHandler
{
Asserts = async content =>
Expand All @@ -462,24 +476,25 @@ public async Task MultipartUploadShouldWorkWithObjects()

Assert.Equal("theObjects", parts[0].Headers.ContentDisposition.Name);
Assert.Null(parts[0].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[0].Headers.ContentType.MediaType);
var result0 = JsonConvert.DeserializeObject<ModelObject>(await parts[0].ReadAsStringAsync());
Assert.Equal(mediaType, parts[0].Headers.ContentType.MediaType);
var result0 = await serializer.DeserializeAsync<ModelObject>( parts[0]).ConfigureAwait(false);
Assert.Equal(model1.Property1, result0.Property1);
Assert.Equal(model1.Property2, result0.Property2);


Assert.Equal("theObjects", parts[1].Headers.ContentDisposition.Name);
Assert.Null(parts[1].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[1].Headers.ContentType.MediaType);
var result1 = JsonConvert.DeserializeObject<ModelObject>(await parts[1].ReadAsStringAsync());
Assert.Equal(mediaType, parts[1].Headers.ContentType.MediaType);
var result1 = await serializer.DeserializeAsync<ModelObject>(parts[1]).ConfigureAwait(false);
Assert.Equal(model2.Property1, result1.Property1);
Assert.Equal(model2.Property2, result1.Property2);
}
};

var settings = new RefitSettings()
{
HttpMessageHandlerFactory = () => handler
HttpMessageHandlerFactory = () => handler,
ContentSerializer = serializer
};

var fixture = RestService.For<IRunscopeApi>(BaseAddress, settings);
Expand Down Expand Up @@ -519,22 +534,22 @@ public async Task MultipartUploadShouldWorkWithMixedTypes()
Assert.Equal("theObjects", parts[0].Headers.ContentDisposition.Name);
Assert.Null(parts[0].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[0].Headers.ContentType.MediaType);
var result0 = JsonConvert.DeserializeObject<ModelObject>(await parts[0].ReadAsStringAsync());
var result0 = JsonConvert.DeserializeObject<ModelObject>(await parts[0].ReadAsStringAsync().ConfigureAwait(false));
Assert.Equal(model1.Property1, result0.Property1);
Assert.Equal(model1.Property2, result0.Property2);


Assert.Equal("theObjects", parts[1].Headers.ContentDisposition.Name);
Assert.Null(parts[1].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[1].Headers.ContentType.MediaType);
var result1 = JsonConvert.DeserializeObject<ModelObject>(await parts[1].ReadAsStringAsync());
var result1 = JsonConvert.DeserializeObject<ModelObject>(await parts[1].ReadAsStringAsync().ConfigureAwait(false));
Assert.Equal(model2.Property1, result1.Property1);
Assert.Equal(model2.Property2, result1.Property2);

Assert.Equal("anotherModel", parts[2].Headers.ContentDisposition.Name);
Assert.Null(parts[2].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[2].Headers.ContentType.MediaType);
var result2 = JsonConvert.DeserializeObject<AnotherModel>(await parts[2].ReadAsStringAsync());
var result2 = JsonConvert.DeserializeObject<AnotherModel>(await parts[2].ReadAsStringAsync().ConfigureAwait(false));
Assert.Equal(2, result2.Foos.Length);
Assert.Equal("bar1", result2.Foos[0]);
Assert.Equal("bar2", result2.Foos[1]);
Expand All @@ -552,7 +567,7 @@ public async Task MultipartUploadShouldWorkWithMixedTypes()
Assert.Equal("anEnum", parts[4].Headers.ContentDisposition.Name);
Assert.Null(parts[4].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[4].Headers.ContentType.MediaType);
var result4 = JsonConvert.DeserializeObject<AnEnum>(await parts[4].ReadAsStringAsync());
var result4 = JsonConvert.DeserializeObject<AnEnum>(await parts[4].ReadAsStringAsync().ConfigureAwait(false));
Assert.Equal(AnEnum.Val2, result4);

Assert.Equal("aString", parts[5].Headers.ContentDisposition.Name);
Expand All @@ -564,7 +579,7 @@ public async Task MultipartUploadShouldWorkWithMixedTypes()
Assert.Equal("anInt", parts[6].Headers.ContentDisposition.Name);
Assert.Null(parts[6].Headers.ContentDisposition.FileName);
Assert.Equal("application/json", parts[6].Headers.ContentType.MediaType);
var result6 = JsonConvert.DeserializeObject<int>(await parts[6].ReadAsStringAsync());
var result6 = JsonConvert.DeserializeObject<int>(await parts[6].ReadAsStringAsync().ConfigureAwait(false));
Assert.Equal(42, result6);

}
Expand Down Expand Up @@ -615,7 +630,7 @@ public async Task MultipartUploadShouldWorkWithHttpContent()
Assert.Equal("myName", parts[0].Headers.ContentDisposition.Name);
Assert.Equal("myFileName", parts[0].Headers.ContentDisposition.FileName);
Assert.Equal("application/custom", parts[0].Headers.ContentType.MediaType);
var result0 = await parts[0].ReadAsStringAsync();
var result0 = await parts[0].ReadAsStringAsync().ConfigureAwait(false);
Assert.Equal("some text", result0);
}
};
Expand Down
23 changes: 23 additions & 0 deletions Refit.Tests/RequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ public interface IRestMethodInfoTests
[Patch("/foo/{id}")]
IObservable<string> PatchSomething(int id, [Body] string someAttribute);

[Post("/foo/{id}")]
Task<ApiResponse<bool>> PostReturnsApiResponse(int id);

[Post("/foo/{id}")]
Task<bool> PostReturnsNonApiResponse(int id);

[Post("/foo")]
Task PostWithBodyDetected(Dictionary<int, string> theData);
Expand Down Expand Up @@ -377,6 +382,24 @@ public void UsingThePatchAttributeSetsTheCorrectMethod()

Assert.Equal("PATCH", fixture.HttpMethod.Method);
}

[Fact]
public void ApiResponseShouldBeSet()
{
var input = typeof(IRestMethodInfoTests);
var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostReturnsApiResponse)));

Assert.True(fixture.IsApiResponse);
}

[Fact]
public void ApiResponseShouldNotBeSet()
{
var input = typeof(IRestMethodInfoTests);
var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostReturnsNonApiResponse)));

Assert.False(fixture.IsApiResponse);
}
}

[Headers("User-Agent: RefitTestClient", "Api-Version: 1")]
Expand Down
Loading
0