I've implemented a Web API.
<authentication mode="None" />
I'm using Basic authorization, and set the Thread.CurrentPrincipal in my AuthorizeAttribute.
The first time after starting/debugging the application, I submit a request, set the Thread.CurrentPrincipal (with IsAuthenticated = true) server-side, and IsAuthenticated returns true in my controller, as expected. Any request after this, however, sets the Thread.CurrentPrincipal as normal, but by time the execution hits my controller methods, the controllers' User.Identity property has been changed, and IsAuthenticated = false.
I can't figure out why IsAuthenticated=true for the first time after starting the application only?! It should be every time, as I'm setting the Thread.CurrentPrinciple manually, but somewhere between there and hitting my controller, it is being replaced!
UPDATE
It's something to do with a MediaTypeFormatter that I've added. When I remove the formatter, I don't get the issue. The formatter's code that gets executed is below:
public override Task<object> ReadFromStreamAsync(Type type, System.IO.Stream webStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
return Task.Factory.StartNew(() =>
{
string temporaryFilePath = Path.Combine(TemporaryDirectory, Path.GetRandomFileName());
using (FileStream fileStream = new FileStream(temporaryFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
{
webStream.CopyTo(fileStream);
}
return (object)new CustomFile(temporaryFilePath);
});
}