// 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.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNet.Localization
{
///
/// Enables automatic setting of the culture for s based on information
/// sent by the client in headers and logic provided by the application.
///
public class RequestLocalizationMiddleware
{
private readonly RequestDelegate _next;
private readonly RequestLocalizationOptions _options;
///
/// Creates a new .
///
/// The representing the next middleware in the pipeline.
/// The representing the options for the .
public RequestLocalizationMiddleware([NotNull] RequestDelegate next, [NotNull] RequestLocalizationOptions options)
{
_next = next;
_options = options;
}
///
/// Invokes the logic of the middleware.
///
/// The .
/// A that completes when the middleware has completed processing.
public async Task Invoke([NotNull] HttpContext context)
{
var requestCulture = _options.DefaultRequestCulture ??
new RequestCulture(CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture);
IRequestCultureProvider winningProvider = null;
if (_options.RequestCultureProviders != null)
{
foreach (var provider in _options.RequestCultureProviders)
{
var result = await provider.DetermineRequestCulture(context);
if (result != null)
{
requestCulture = result;
winningProvider = provider;
break;
}
}
}
context.Features.Set(new RequestCultureFeature(requestCulture, winningProvider));
SetCurrentThreadCulture(requestCulture);
await _next(context);
}
private static void SetCurrentThreadCulture(RequestCulture requestCulture)
{
#if DNX451
Thread.CurrentThread.CurrentCulture = requestCulture.Culture;
Thread.CurrentThread.CurrentUICulture = requestCulture.UICulture;
#else
CultureInfo.CurrentCulture = requestCulture.Culture;
CultureInfo.CurrentUICulture = requestCulture.UICulture;
#endif
}
}
}