Net framework ошибка 403
Я только что создал новый пустой веб-сайт в Visual Studio 2012 и нажал на кнопку «Выполнить» (т.е. просмотр в браузере), и я получаю эту ошибку:
Я вошел в IIS и нажал на просмотр каталогов, а затем убедился, что просмотр каталогов был включен, но я все еще получаю эту ошибку. Я не могу понять это?
Проект веб-сайта, который я только что создал, не указан на веб-сайтах по умолчанию в IIS Manager, что, на мой взгляд, было странно.
Как мне избавиться от этой ошибки?
Вы запускали или просматривали в браузере ? 2 разные вещи. Если это проект MVC, то вы, возможно, пытались просмотреть view в браузере?
сохраните это в своем файле веб-конфигурации, затем переименуйте add value = "yourwebformname.aspx"
Я работал над этим проектом несколько месяцев - никогда не нуждался в этой линии. Я опубликовал сайт сегодня, и он больше не будет работать в режиме отладки . Добавленная эта строка заставляет это работать снова! Я проверил SVN - определенно никогда не нуждался в этом раньше. WTF !? В любом случае, спасибо, что потерял только час :)
Эта проблема возникает из-за того, что на веб-сайте не Directory Browsing включена эта функция, а документ по умолчанию не настроен. Чтобы решить эту проблему, используйте один из следующих методов. Чтобы решить эту проблему, я выполнил шаги, описанные в способе 1, как указано на странице поддержки MS, и рекомендованный метод.
Способ 1. Включите функцию просмотра каталогов в IIS (рекомендуется)
Запустите IIS Manager. Для этого нажмите кнопку Пуск, выберите пункт Выполнить, введите inetmgr.exe и нажмите кнопку ОК.
В диспетчере IIS разверните имя сервера, разверните веб-сайты, а затем щелкните веб-сайт, который вы хотите изменить.
В представлении «Функции» дважды щелкните «Просмотр каталога».
На панели «Действия» нажмите «Включить».
Если это не сработает, возможно, у вас возникла другая проблема, чем просто проблема со списком каталогов. Так что следуйте ниже шаг,
Способ 2: добавить документ по умолчанию
Чтобы решить эту проблему, выполните следующие действия.
- Запустите IIS Manager. Для этого нажмите кнопку Пуск, выберите пункт Выполнить, введите inetmgr.exe и нажмите кнопку ОК.
- В диспетчере IIS разверните имя сервера, разверните веб-сайты, а затем щелкните веб-сайт, который вы хотите изменить.
- В представлении «Функции» дважды щелкните «Документ по умолчанию».
- На панели «Действия» нажмите «Включить».
- В поле Имя файла введите имя документа по умолчанию и нажмите кнопку ОК.
Способ 3: включить функцию просмотра каталогов в IIS Express
Примечание. Этот метод предназначен для веб-разработчиков, которые сталкиваются с проблемой при использовании IIS Express.
Следуй этим шагам:
Откройте командную строку и перейдите в папку IIS Express на вашем компьютере. Например, перейдите в следующую папку в командной строке: C:\Program Files\IIS Express
Введите следующую команду и нажмите клавишу ВВОД:
appcmd set config /section:system.webServer/directoryBrowse /enabled:true
Это должен быть принят ответ. Метод 2 работал для меня. Сначала я создал пустой веб-сайт, а затем добавил веб-форму с именем «WebForm1.aspx». Следовательно, мне нужно добавить это имя в список документов по умолчанию. Спасибо.
Перейдите в cmd и введите это:
Это установит правильную версию, и IIS поймет, просмотр каталога MVC
27 Answers 27
keep this into your web config file then rename the add value="yourwebformname.aspx"
I've been working on this project for months - never needed this line. I published the site today and it wouldn't run in debug anymore. Added this line makes it work again! I checked SVN - definitely never needed it before. WTF!? Thanks anyway, only wasted an hour :)
This achieved nothing but wasting my time. Yeah, sure the aspx page loads but what good does that do me when it provides no access to my application?
it was working until I changed web.config.. so issue shows up. Changed web.config back to original with no avail. Added suggested option works..
This problem occurs because the Web site does not have the Directory Browsing feature enabled, and the default document is not configured. To resolve this problem, use one of the following methods. To resolve this problem, I followed the steps in Method 1 as mentioned in the MS Support page and its the recommended method.
Method 1: Enable the Directory Browsing feature in IIS (Recommended)
Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
In the Features view, double-click Directory Browsing.
In the Actions pane, click Enable.
If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,
Method 2: Add a default document
To resolve this problem, follow these steps:
- Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
- In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
- In the Features view, double-click Default Document.
- In the Actions pane, click Enable.
- In the File Name box, type the name of the default document, and then click OK.
Method 3: Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
Follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt: C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:system.webServer/directoryBrowse /enabled:true
But when it opens the page error : 403 Forbidden comes. What might cause this? What I need to check and edit before publishing?
A resource on the server your program is tying to access is forbidden
It looks to me that is dealing with a resource issue. No matter how you look at it, the server is rejecting the access from the client. The Web server is the one returning the 403. Now it's up to you to figure out why and the solution.
So it's better for me to contact web hosting server and require to fix. Because I paid for my hosting, and they mustn't forbid access to my website, they configured something incorrectly.
I would say contact the Web hosting provider about the 403 issue, since you have no control over the server resources and access.
The 502.5 error generally accompanies a bit more information like the application failed to start. I see this error when deploying a newer version of Core than what's installed on the server. Anyway, read the troubleshooting docs.
Did you ever deploy this solution to local IIS on your development machine, you tested it and it worked, before you deployed it to the hosting provider?
Of course, before publishing to web hosting I published to local host many times during development of the application, and of course, most time with success, and even there were several times that I face this error, and solved it by doing nothing but just re-running application (debug - start without debugging), and it became live as usual. But in real publishing, this isn't working. I wrote this issue to hosting, and they're checking the version compatibility with theirs in server, and waiting reply from them. Hope this will be solved as soon as possible.
But in real publishing, this isn't working. I wrote this issue to hosting, and they're checking the version compatibility with theirs in server, and waiting reply from them. Hope this will be solved as soon as possible.
What are you talking about real publishing, becuase if you actually published the program to local IIS I am not talking about IIS Express, then you actually published the solution to local IIS that is the same kind of IIS the hosting provider has a real Web server? I mean you would have installed local IIS off of Control Panel, Add Program Features, Add Windows Components and installed IIS. Have you ever done that?
No I did using IIS Express via Visual Studio.
No I did using IIS Express via Visual Studio.
Well based on your O/S can you install IIS on you computer. If I am not mistaken, Win10 Home is the only Home version of the Winnows O/S that IIS that can be installed from the installation media. I have always used a professional version of the Windows workstation O/S so check me on the other Home versions if you are using a Home version.
The publishing to local IIS on your machine should work the same way for all the Core 2.x versions.
You can use VS to develop, test and debug the Core Web project out on local IIS on your development machine.
Thanks for your info.
User-474980206 posted
This is the reply that I've got from my hosting server:
Upon reviewing the event viewer logs the site fails to connect to the database due to an invalid username/password combination:
CoreCLR Version: 4.6.27019.6
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Data.SqlClient. SqlException: Cannot open database "foroffer_" requested by the login. The login failed.
Login failed for user 'PURPLE\IWPD_504(foroffer)'.
Please ensure that the password that the web config file is trying to use to log into the database is correct.
I have checked and do not see any details of database in web.config file.
As long as I know it is appsetting.json instead of it.
The connectionstring should in be in the appsettins.json and Startup.cs should address accessing the connectionstring using a service.
If you are following the publishing link I gave you, then all the files needed were placed in the published folder, and you should not deviate from the instructions.
The connection string is not correct for when you moved the solution to the hosting provider site, and you need to contact the provider about what the connectionstring should look like when you move the files to the hosting site. The appsettings.json file is a text file that you can use an editor and change the connectionstring and save it.
The issue is with the deployment or your code. You should be able to change the connection string to point to the remote SQL server and run migrations from your desktop. This should get the DB created or populated.
First, make sure your DB connection works by connecting to the DB using SQL Server Management Studio or through Visual Studio's Server Explorer or SQL Object Explorer.
FaridGN
I have never used a hosting provider. What means does the provider have other than one using some migration to establish a database on its database server?
I would assume the hosting client is able to give the hosting provider the MDF file developed locally so that the file could be attached to the provider's database engine so that the database can be used, which would eliminate the migration altogether.
That would be my approach, and I would just be giving the hosting provider just the files and no migration.
DA924
Connecting to SQL Server is no different from working in a Dev Shop or paying for hosting. It's just DNS and SQL Services running on port 1433 (default).
It sounds like the connection string is incorrect. I recommend testing the SQL connection from the desktop. Once connected, run migrations or execute DDL, DML to get the tables built and populated. Depending on how you coded this, the connection string can be hard coded inside the DbContext file. YMake sure the connection string in the appsetting.json file is the one being used.
Я написал xml-граббер для получения / декодирования xml-файлов с веб-сайта. В основном он работает нормально, но всегда возвращает ошибку:
"Удаленный сервер возвратил ошибку: (403) Запрещено."
И исключение - это бросок в метод GetResponse. Как я могу узнать, что случилось?
Возможно, в вашем запросе отсутствует заголовок, который требуется серверу. Я запросил страницу в браузере, записал точный запрос с помощью Fiddler, затем удалил заголовок User-Agent и повторно отправил запрос. В результате было получено 403 ответа.
Это часто используется серверами в попытке предотвратить создание сценариев для своих сайтов, как это делаете вы; o)
В этом случае заголовок сервера в ответе 403 - «AkamaiGHost», который указывает на граничный узел из некоторого решения облачной безопасности от Akamai. Возможно, правило WAF для предотвращения ботов запускает ошибку 403.
Похоже, что добавление любого значения в заголовок User-Agent подойдет для этого сайта. Например, я установил его на «определенно-не-скребок для экрана», и, похоже, это работает нормально.
Интернет - это не черный ящик
В моем конкретном случае серверу не понравился не заголовок UserAgent, а заголовок Accept.
Вы можете использовать вкладку сети браузеров инструментов разработчика, чтобы увидеть, какие заголовки должны быть правильными.
Ваш запрос проходит через прокси-сервер? Если да, добавьте следующую строку перед вызовом GetResponse() .
Понятно, что URL работает из браузера. Это просто не работает из кода. Похоже, что сервер принимает / отклоняет запросы на основе пользовательского агента, вероятно, как очень простой способ предотвратить сканирование.
Чтобы пройти, просто установите для свойства UserAgent то, что оно распознает, например:
Кажется, это работает.
Скорее всего, у вас нет разрешений на доступ к ресурсу, к которому вы пытаетесь обратиться. Поэтому вам нужно получить необходимые учетные данные для выполнения требуемого действия.
Имя "class" не существует в текущем контексте
Часто эта ошибка возникает из-за того, что class ссылается на вспомогателя, но вспомогательный компонент не установлен. Например, если вы попытаетесь использовать вспомогательный компонент, но если пакет не установлен из NuGet, вы увидите эту ошибку. Используйте коллекцию в WebMatrix, чтобы найти и установить вспомогателя.
Этот тип страницы не обслуживается (ошибка сервера в приложении /)
Версии программного обеспечения
Этот раздел состоит из следующих подразделов.
Проблемы с кодом Razor
Чтобы вызвать этот метод, свойство Membership.Provider должно быть экземпляром ExtendedMembershipProvider.
Эта ошибка может указывать на то, что класс не AspNetSqlMembershipProvider настроен. (Симптом заключается в том, что сайт работает хорошо локально, но выдает эту ошибку при публикации на сервере поставщика услуг размещения.) Одним из исправлений этой проблемы является явное включение простого членства, добавив следующее в файл Web.config сайта:
Проблемы с безопасностью и членством
Проблемы с запущенными страницами
У вас нет разрешения на просмотр этого каталога или страницы с использованием предоставленных учетных данных.
Убедитесь, что в корневом каталоге веб-сайта есть хотя бы один CSHTML-файл .
Веб-сервер настроен для не перечисления содержимого этого каталога.
Эта ошибка может возникнуть, если вы запрашиваете защищенный ресурс (например, файл Web.config ) или находится в защищенной папке (например, App_Data или App_Code).
Запрошенный контент представляется скриптом и не будет обслуживаться статическим обработчиком файлов.
Модуль фильтрации запросов настроен для запрета расширения файла.
Эта ошибка может возникнуть, если расширения CSHTML или VBHTML были явно заблокированы на сервере. Симптомом этой проблемы является то, что URL-адреса работают, если они не включают расширение, но URL-адреса, включающие CSHTML или VBHTML , не работают. Возможным решением является повторное включение расширений в файлеWeb.config сайта. В следующем примере показано, как включить расширение CSHTML .
Модуль фильтрации запросов настроен на запрет пути в URL-адресе, содержавшемся в разделе hiddenSegment.
Эта ошибка может возникнуть, если вы запрашиваете защищенный ресурс (например, файл Web.config ) или находится в защищенной папке (например, App_Data или App_Code).
Проблемы с отправкой электронной почты
Сбой отправки почты.
Сбой попытки подключения из-за того, что подключенная сторона не ответила должным образом через период времени или не удалось установить подключение, так как подключенный узел не ответил
Эта ошибка обычно означает, что приложению не удалось подключиться к SMTP-серверу. Проверьте имя сервера и номер порта.
Почтовый ящик недоступен. Ответ сервера: 5.1.0 отправитель отклонен: недопустимый домен отправителя
Указанная строка не находится в форме, необходимой для адреса электронной почты.
I just created a new empty website in Visual Studio 2012 and clicked on run (i.e view in browser) and I get this error :
I went into IIS and clicked on Directory browsing and then ensured that Directory browsing was enabled but I still get this error. I can't figure it out ?
The website project I just created is not listed in Default web sites in IIS Manager which I thought was odd.
How do I get rid of this error ?
Did you run or view in browser? 2 different things. If this is an MVC project, then you might have tried to view a view in a browser?
Читайте также: