尝试连接到“本地主机”时,为什么会出现“访问被拒绝”错误?

时间:2019-10-20 23:33:25

标签: c# server

我正在制作一个应用程序,它将c#中的html文件内容写入服务器。事实是它应该可以工作,但是某种程度上却不能。

我已经多次检查代码,从教程中复制了准确​​的代码,并对其进行了修改以满足我的需要;但是以某种方式它仍然不起作用(即使以前已经起作用)。

public Server(string filename) 
        {
            chatNames = filename;
            try
            {
                string content;
                HttpListener server = new HttpListener();// this is the http server
                server.IgnoreWriteExceptions = true;
                server.Prefixes.Add("http://127.0.0.1/");
                server.Prefixes.Add("http://localhost/");

                server.Start();

                while (true)
                {
                    content = FileR(filename);
                    HttpListenerContext context = server.GetContext();
                    //context: provides access to httplistener's response

                    HttpListenerResponse response = context.Response;
                    //the response tells the server where to send the datas

                    string page = Directory.GetCurrentDirectory() + "/" + filename + ".txt";
                    //this will get the page requested by the browser

                    if (page == string.Empty)  //if there's no page, we'll say it's index.html
                        page = "index.html";

                    TextReader tr = new StreamReader(page);
                    string msg = tr.ReadToEnd();  //getting the page's content

                    byte[] buffer = Encoding.UTF8.GetBytes(content);
                    //then we transform it into a byte array

                    response.ContentLength64 = buffer.Length;  // set up the messasge's length
                    Stream st = response.OutputStream;  // here we create a stream to send the message
                    st.Write(buffer, 0, buffer.Length); // and this will send all the content to the browser

                    context.Response.Close();  // here we close the connection
                    hasRan = true;
                }
            } catch (Exception e)
            {
                hasRan = false;
                error = e.Message;
            }
        }

        private string FileR(string name)
        {
            string content = string.Empty;
            FileInfo fi = new FileInfo(chatNames);

            if (IsFileLocked(fi))
            {
                using (StreamReader sr = new StreamReader(chatNames))
                {

                    //viewMessage.TextAlignment = TextAlignment.Left;
                    content = sr.ReadToEnd();

                }
            }
            else
            {
                content = "Please try again later";
                Thread.Sleep(350);
            }
            return content;
        }

我在网上到处都是,但仍然找不到能回答我问题的东西。如果我错过了在线活动,请通知。

1 个答案:

答案 0 :(得分:1)

选项1.以管理员模式运行该应用程序。

选项2.在非管理员模式下运行HttpListener。您需要做的就是授予对特定URL的权限。例如

`netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user`