【问题标题】:Pass a remote object to a remote method in C#将远程对象传递给 C# 中的远程方法
【发布时间】:2024-06-08 20:20:01
【问题描述】:

我正在尝试将远程对象作为参数传递给远程方法,但是当远程对象尝试在接收到的远程对象上运行方法时,我得到了一个安全异常。

这是一个示例远程对象:

public class SharpRemotingDLL : MarshalByRefObject
{
    public String getRemoteMessage(SharpRemotingDLL server)
    {
        // the exception is raised here
        return server.getMessage();
    }

    public String getMessage()
    {
         return "Hello World!";
    }
}

这是服务器启动器(它的两个实例正在运行,一个在 127.0.0.10025 上,另一个在 127.0.0.10026 上):

public static int Main(string[] args)
{
    TcpServerChannel channel;
    channel = new TcpServerChannel(10025);
    ChannelServices.RegisterChannel(channel, false);
    RemotingConfiguration.RegisterWellKnownServiceType(
        typeof(SharpRemotingDLL),
        "SharpRemotingDLL",
        WellKnownObjectMode.Singleton);
    Console.ReadLine();
    return 0;
}

这是客户端:

static void Main(string[] args)
{
    SharpRemotingDLL server0 = (SharpRemotingDLL)
        Activator.GetObject(typeof(SharpRemotingDLL),
        "tcp://localhost:10025/SharpRemotingDLL");
    SharpRemotingDLL servers[1] = (SharpRemotingDLL)
        Activator.GetObject(typeof(SharpRemotingDLL),
        "tcp://localhost:10026/SharpRemotingDLL");
    Console.WriteLine(server0.getRemoteMessage(server1));
}

如何正确地将 server1 作为参数传递给 getRemoteMessage 方法?

【问题讨论】:

    标签: c# remoting


    【解决方案1】:

    vbigiani,

    这篇文章应该对您的问题有所了解:

    http://weblogs.asp.net/jan/archive/2003/06/01/8106.aspx

    如果这不起作用,您可以在此处获得几个相关的 Google 点击:

    Because of security restrictions, the type System.Runtime.Remoting.ObjRef cannot be accessed

    【讨论】:

      【解决方案2】:

      我以前写过这种代码,但是我从来没有尝试过以这种方式将一个服务器对象传递给另一个服务器对象。我不是安全专家,但我能理解为什么不允许这样做。

      您应该直接从 Server1 获取消息,而不是要求另一个远程服务器返回它。换句话说,您的消息检索逻辑需要在客户端中。

      【讨论】:

      • 这只是一些示例代码来演示问题。在我的真实代码中,SharpRemotingDLL 是一个导出基本文件操作(CreateFile、ReadFile 等)的类,我使用类似的合成器在两个服务器之间实现 CopyFile 和 MoveFile:客户端使用 server1.CopyFile("foo.txt",server2 ) CopyFile 方法: public void CopyFile(String name, SharpRemotingDLL server) { server.WriteFile(name,this.ReadFile(name)); }
      • 我无法准确翻译,因为我的操作系统是意大利语的,并且在谷歌上搜索错误消息是没有帮助的。无论如何:pastebin.com/m6219b56f
      最近更新 更多