Почему я получаю сообщение об ошибке «Отказано в доступе» при попытке подключиться к «localhost»? - PullRequest
1 голос
/ 21 октября 2019

Я создаю приложение, которое записывает некоторое содержимое файла на сервер в виде html в c #. Дело в том, что это должно работать, но это как-то не работает.

Я проверял код несколько раз, скопировал точный код из учебника и изменил его в соответствии со своими потребностями;но почему-то это все равно не работает (хотя раньше это работало).

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 Ответ

1 голос
/ 21 октября 2019

Вариант 1. Запустите приложение в режиме администратора.

Вариант 2. Запустите HttpListener в режиме без прав администратора. Все, что вам нужно сделать, это предоставить разрешения для конкретного URL. например,

`netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user`
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...