Two-way communication between AppDomains inside of IIS Requests

前端 未结 1 1354
自闭症患者
自闭症患者 2021-01-14 20:12

I\'m working on an ASP.NET app, and we want to add the ability to call customer script during some of the requests. Since we don\'t trust this script, we are spawning a chi

1条回答
  •  攒了一身酷
    2021-01-14 20:50

    I think I've found a simple technique for a child AppDomain to alter the state in the parent AppDomain without using WCF or mscoree.dll. Rereading the first post above, I see he does mention it as a possibility, but rejects it for reasons that are not clear to me. The trick is to create an object derived from MarshalByRefObject in the parent, obtain an ObjectHandle to it, and then pass that ObjectHandle to the child AppDomain. The child can then unwrap the handle to get a proxy, and can then call methods which will alter the state of the object in the parent. Here's a code sample:

    class Program
    {
        public class ParentFacade : MarshalByRefObject
        {
            public List Collection { get; set; }
            public void AddElement(string el)
            {
                Collection.Add(el);
            }
        }
    
        public class ChildFacade : MarshalByRefObject
        {
            public void AlterParentState(ObjectHandle handle)
            {
                var parent = handle.Unwrap() as ParentFacade;
                parent.AddElement("Message from child");
            }
        }
    
        static void Main(string[] args)
        {
            var child = AppDomain.CreateDomain("child");
            var childFacadeType = typeof(ChildFacade);
            var childProxy = child.CreateInstanceAndUnwrap(childFacadeType.Assembly.FullName, childFacadeType.FullName) as ChildFacade;
    
            var parentColl = new List();
            var facade = new ParentFacade();
            facade.Collection = parentColl;
            var facadeHandle = new ObjectHandle(facade);
            childProxy.AlterParentState(facadeHandle);
    
            foreach (var item in parentColl)
                Console.WriteLine(item);
        }
    }
    

    This code shows that a method in the child was able to alter the state of objects in the parent. This particular example isn't terribly useful, but this is very powerful when you are setting up a sandbox, and include .dll's in the child assembly that you don't trust. The untrusted assembly can call methods in the ChildFacade and thereby alter the state in the parent in a controlled and safe way.

    0 讨论(0)
提交回复
热议问题