1

我正在使用 .NET Framework 4.6.1、C# 和 WinForms(离线桌面应用程序)开发一个项目。我来自 web-dev,我对桌面应用程序不是很熟悉。

对于应用程序的一部分,我正在使用HttpSelfHostServer为我提供 API 功能。

        var config = new HttpSelfHostConfiguration("http://localhost:8080/api/");

        config.Routes.MapHttpRoute(
        "default", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
        config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));

        // pass in config to new server instance
        HttpSelfHostServer server = new HttpSelfHostServer(config);

        server.OpenAsync().Wait();
        Console.WriteLine("Press Enter to quit.");
        Console.ReadLine();

这会引发错误:AddressAccessDeniedException: HTTP could not register URL http://+:8080/api/. Your process does not have access rights to this namespace

我努力了:

  1. 以管理员身份使用netsh http add urlacl url=http://+:8080/api/ user=everyone来自 CMD 的命令来解决问题,但这是一个糟糕的解决方案。应用程序的最终用户不必使用命令行。

  2. 以编程方式运行上述命令:

         var netshProcess = new Process
         {
             StartInfo =
             {
                 FileName = "cmd",
                 Arguments = "netsh http add urlacl url=http://+:8080/api/ user=everyone",
                 UseShellExecute = true,
                 Verb = "runas",
    
                 //WindowStyle = ProcessWindowStyle.Hidden
             }
         };
    
         try
         {
             netshProcess.Start();
    
         }
         catch (Exception portRegisterError)
         {
             Console.WriteLine(portRegisterError);
             throw;
         }
    

根据我发现的类似问题,这应该以管理员权限执行命令,但在我的情况下,它所做的只是:打开 Windows 用户访问控制以确认,然后打开命令提示符窗口,没有传入任何命令(导致抛出相同的AddressAccessDeniedException)。

我错过了什么?

我知道这一切看起来像是一种“hacky”的做事方式,但由于各种原因,我在这方面没有太多选择,我只需要以一种或另一种方式完成这项工作,而不要求最终用户做事.

我会提出任何建议。

非常感谢。

4

0 回答 0