1 //------------------------------------------------------------------------------
2 // <copyright file="ExecutionContextUtil.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 //------------------------------------------------------------------------------
7 namespace System.Web.Util {
9 using System.Reflection;
10 using System.Security.Permissions;
11 using System.Threading;
13 // This class contains utility methods for dealing with security contexts when crossing AppDomain boundaries.
15 [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
16 internal static class ExecutionContextUtil {
18 private static readonly ContextCallback s_actionToActionObjShunt = obj => ((Action)obj)();
19 private static readonly ExecutionContext s_dummyDefaultEC = GetDummyDefaultEC();
21 [ReflectionPermission(SecurityAction.Assert, MemberAccess = true)]
22 private static ExecutionContext GetDummyDefaultEC() {
23 // The ExecutionContext.PreAllocatedDefault property is special-cased by ExecutionContext to be a blank context and to allow multiple invocation.
24 PropertyInfo propInfo = typeof(ExecutionContext).GetProperty("PreAllocatedDefault", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
26 if (propInfo == null) {
27 throw new Exception(SR.GetString(SR.Type_doesnt_have_property, typeof(ExecutionContext).FullName, "PreAllocatedDefault"));
30 return (ExecutionContext) propInfo.GetValue(null, null);
33 // Removes all context associated with the current thread (call context, IPrincipal, etc.) and invokes the provided callback.
34 // The intent of this method is to get any user-provided context off the current thread before crossing an AppDomain boundary,
35 // as the existence of that context could lead to behavioral problems (see DevDiv #205764) or security problems (see DevDiv #206598).
36 internal static void RunInNullExecutionContext(Action callback) {
37 ExecutionContext.Run(s_dummyDefaultEC, s_actionToActionObjShunt, callback);