The setup
- I've a WebAPI Controller, that makes a call to a web endpoint, using HttpClient.PostAsJsonAsync
- Let's say, that the response of the controller method and the request to the web endpoint is the same entity type
- I've a custom JsonConverter registered for this entity type. I have a use case to access the HttpContext in this converter
The issue: when the converter's WriteJson method is invoked, to serialize the entity during HttpClient.PostAsJsonAsync, HttpContext.Current is NULL.
However, when the same flow is invoked when serializing the entity in WebAPI response the context is available fine.
Has anyone faced similar issues before? I'm not sure what the cause of this issue is and what could be possible solutions / workarounds.
I am able to re-produce this behavior with a sample WebAPI project. Here are the relevant code snips:
[JsonConverter(typeof(EntityConverter))]
public interface IEntity
{
}
public class Entity : IEntity
{
}
public class EntityConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// httContext is NULL when deserializing the HttpClient request entity
var httpContext = HttpContext.Current;
var principal = httpContext?.User;
Console.WriteLine("");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return new Entity();
}
public override bool CanConvert(Type objectType)
{
return typeof(Entity) == objectType;
}
}
public class ValuesController : ApiController
{
// POST api/values
public async Task<HttpResponseMessage> Post([FromBody]string value)
{
HttpClient client = new HttpClient();
var message = await client.PostAsJsonAsync("http://example.com", new Entity());
Console.WriteLine(message);
return Request.CreateResponse(HttpStatusCode.Created, new Entity());
}
}