// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Owin;
using Microsoft.Owin.Security;
namespace System.Net.Http
{
///
/// Provides extension methods for the class.
///
[EditorBrowsable(EditorBrowsableState.Never)]
public static class OwinHttpRequestMessageExtensions
{
private const string OwinEnvironmentKey = "MS_OwinEnvironment";
private const string OwinContextKey = "MS_OwinContext";
/// Gets the OWIN context for the specified request.
/// The HTTP request message.
///
/// The OWIN environment for the specified context, if available; otherwise .
///
public static IOwinContext GetOwinContext(this HttpRequestMessage request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
IOwinContext context;
if (!request.Properties.TryGetValue(OwinContextKey, out context))
{
// If the OWIN context is not available, try to create by upgrading an OWIN environment property
// instead.
IDictionary environment;
if (request.Properties.TryGetValue>(OwinEnvironmentKey, out environment))
{
context = new OwinContext(environment);
SetOwinContext(request, context);
request.Properties.Remove(OwinEnvironmentKey);
}
}
return context;
}
/// Sets the OWIN context for the specified request.
/// The HTTP request message.
/// The OWIN context to set.
public static void SetOwinContext(this HttpRequestMessage request, IOwinContext context)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
request.Properties[OwinContextKey] = context;
// Make sure only one of the two properties exists (single source of truth).
request.Properties.Remove(OwinEnvironmentKey);
}
/// Gets the OWIN environment for the specified request.
/// The HTTP request message.
///
/// The OWIN environment for the specified request, if available; otherwise .
///
public static IDictionary GetOwinEnvironment(this HttpRequestMessage request)
{
IOwinContext context = GetOwinContext(request);
if (context == null)
{
return null;
}
return context.Environment;
}
/// Sets the OWIN environment for the specified request.
/// The HTTP request message.
/// The OWIN environment to set.
public static void SetOwinEnvironment(this HttpRequestMessage request, IDictionary environment)
{
SetOwinContext(request, new OwinContext(environment));
}
internal static IAuthenticationManager GetAuthenticationManager(this HttpRequestMessage request)
{
IOwinContext context = GetOwinContext(request);
if (context == null)
{
return null;
}
return context.Authentication;
}
}
}