Visual studio веб служба недоступна
If I go into the project properties under debug and change the port, then it will connect 1 time. Then if I attempt to connect again, it will give me the same error again. I can then switch the port back to the original and it will load one time, then it will fail any time beyond that, until I switch it again. Anyone have any ideas or fixes they used?
33 Answers 33
I had this problem. There is a hidden folder in directory of project that name is '.vs'. Close the Visual Studio and delete this folder. The problem will be solved.
Yes this too worked for me. People should try this solution first if they stumble across such an issue.
It's amazing how many times just deleting that folder fixes issues like this. Confirming that this fixed this for me in VS2019 on Windows 10.
I installed core 2.0 and updated VS 2017 to 15.4.3 today, had the same error.
I ended up changing the application to run on a different port, it worked for me.
I have tried to delete the vs folder but did not work.
I got the issue when I have copied the solution from one machine to another one. I have deleted "vs" folder that worked for me.
I got the same issue with my solution at some point, but apparently I needed to run VS as Administrator for it to work (maybe clearing the .vs folder would have worked for me as well, but I did not get there)
The error just started appearing for no obvious reason, and I tried the solutions posted here.
I ran the web app from the command line using the dotnet run command to see if that would bring up any meaningful errors, and there was a warning about the URL not being correctly bound. I looked in my projects Properties\launchSettings.json file and noticed that the applicationUrl properties were different.
- Change the values for applicationURL so they are the same
- Close the project and close VS
- Delete the hidden .vs folder (as mentioned in the accepted answer)
- Start up VS as Admin
Your app should work fine.
No clue why, but for me it started working when setting iisSettings > iisExpress > applicationUrl to port 5000 ("http:// localhost:5000") Anyways, thanks for your hint! :)
I was having the issue on Visual Studio 2019 with a clean branch from master. Restarting the PC solved the problem.
My college said he is having the problem about 2 times a month and other tries for solutions did not work.
I tried some of the other suggestions but with no luck. Then I suddenly got an error message (after doing a "clean" I think) claiming a file was locked (in use by another process). I restarted my computer and then it worked again.
It could also just be that there are iisexpress.exe processes hanging around in task manager which were running on the same port.
I've just found a couple and killing them solved this problem for me without needing to delete any .vs folder or changing ports or anything like that.
I gave up, and chose to run the project as self hosted, instead of 'IIS Express' in the play/run drop-down box.
The ports must be different:
Go here in your project: Properties/launchSettings.json open this file and edit the port numbers here. Note: This is where you change the SSL port (two places).
If you are trying to use Azure AD registered applications reply ports and trying to "reuse" your app registration, you might think to simply change the "app's" port so that you don't have to register it in Azure; this will not work. If you are just testing apps and want to reuse a registration then you must make sure that the app you are currently working on is the ONLY one on the port - manually. If you need to test two or more apps then you must register them in Azure AD individually as you would in production.
What worked for me and it is really simple:
- Right-click project
- Properties
- Debug
- App URL: change port to 5000
Done, hope helps someone.
I have solved this issue by adding exclusion to file devenv.exe in windows defender (anti virus, Win10)
how to know this is the issue; when you load project defender will notify in notification unauthorized changes blocked. if this is the issue just add the exception as above mentioned.
Thank you. In my case Windows Defender didn't block first instance of VS, but if I wanted to run two projects (two separate VS windows) the second one hanged.
For me above solutions did not work
But changing the IIS Express Bitness to x64 worked
I encountered this issue. Running VS in admin mode solved this issue for me.
Something else can be running on your port that interferes.
This worked for me!
For me with VS2019, faced this same issue on start running our project. So right clicking on IIS Express icon in notification pane near by DateTime pane in our laptop/Desktop. It will show up all running application, at last can find Exit. Click Exit there and run your project should work. That worked for me, without closing VS19 project.
After playing with netsh configuration trying to make the server accessible from outside, I added a new iplisten entry. The IISExpress showed the error Unable to connect to web server 'IIS Express' which was fixed after deleting the iplisten entry using:
You can view the current list of iplisten entries using
They require running an elevated (administrator) command prompt.
It seems like IISExpress has no error message in this a case.
- If you're hard-coding a specific IP address (not localhost), check that it hasn't changed.
Tried all. didn't work above. changing host in applicationhost.config fixed.
change localhost to 127.0.0.1
It works after I reenter username and password for the application pool's identity account
Setting "Enable SSL" to false in project properties\Debug section worked for me.
It may not completely direct your case, but I just had to restart my (windows) system. The diagnosis of @Turneye may very well be the reason and his solution might accomplish the same result.
I added the localhost option on the applicationhost.config file and run visual studio as administrator and it worked for me.
Ideally you shouldn't have to run Visual Studio as an administrator or with administrative rights. It creates options for malicious code.
Some times running visual studio as administrator solves this issue.
For me worked by changing the applicationUrl in launchsettings.json file to different port number and that url to be same for all places inside this file.
In my case (VS 2019), all I have to do is Rebuild the code before I re-run the app after each code modification.
P.S. I am coding server-side Blazor.
Another solution is to run Visual Studio as an administrator which allows it to override the urlacl.
I was facing the issue multiple times in VS2019, then I realized when I make small edits and restart the IIS Express this problem is more pronounced. Some of the discussion above about ports make me think since I was closing the app by just closing the browser. So I believe the port was not released and it failed the start next time around. I started closing the debug by clicking the "Stop Debugging" button in the VS2019. The issue didn't occur again for me.
I solved this by restart my laptop.
Rebuilding the solution fixed this problem for me.
Changing to "Out of Process" (Right Click Project > Properties > Debug > Web Server Settings > Hosting Model), closing visual studio, deleting the hidden .vs folder (as described in previous comments), and then running IIS Express in VS finally worked. If you ever change it back to "In Process" for testing and it doesn't work, you'll have to delete the .vs folder again after you change it back and close the project.
If you're like me and that got you over one hurdle and into another.
I'm also gonna post my first issue here when trying to run IIS Express from Visual Studio, which was Cannot find C:\Program Files\IIS Express\iisepxress.exe . IIS Express was for some reason installed not only in my Program Files (x86) , but in my second drive ( D:\Program Files (x86) ). After realizing that there is just no way to change where Visual Studio is looking for IIS Express (even though it's also installed on the D drive), I uninstalled IIS Express (which is probably how my dev cert got removed), in RegEdit changed my Program Files directory back to the "C\Program Files" folder (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion > ProgramFilesDir key), and reinstalled IIS Express from Microsoft.
У нас есть решения для распространенных ошибок сети или прокси-сервера, которые могут возникать при установке или использовании Visual Studio за брандмауэром или прокси-сервером.
Ошибка: "Требуется проверка подлинности на прокси-сервере"
Эта ошибка обычно происходит, когда пользователи подключаются к Интернету через прокси-сервер, который блокирует вызовы Visual Studio к некоторым сетевым ресурсам.
Устранение этой ошибки прокси-сервера
Перезапустите Visual Studio. Должно появиться диалоговое окно проверки подлинности прокси. Когда в диалоговом окне появится запрос, введите свои учетные данные.
Если вы хотите использовать учетные данные по умолчанию для прокси-сервера, сделайте следующее:
Найдите файл devenv.exe.config (файл конфигурации devenv.exe) в папке %ProgramFiles%\Microsoft Visual Studio\2017\Enterprise\Common7\IDE или %ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\Common7\IDE.
В файле конфигурации найдите блок и добавьте следующий код:
В proxyaddress=" необходимо вставить правильный адрес прокси-сервера в сети.
Найдите файл devenv.exe.config (файл конфигурации devenv.exe) в папке %ProgramFiles%\Microsoft Visual Studio\2019\Enterprise\Common7\IDE или %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Enterprise\Common7\IDE.
В файле конфигурации найдите блок и добавьте следующий код:
В proxyaddress=" необходимо вставить правильный адрес прокси-сервера в сети.
Ошибка: "Отсутствует подключение к Visual Studio" при попытке сообщить о проблеме
Эта ошибка обычно возникает, когда пользователи подключаются к Интернету через прокси-сервер, который блокирует вызовы Visual Studio к некоторым сетевым ресурсам.
Устранение этой ошибки прокси-сервера
Найдите файл feedback.exe.config (файл конфигурации feedback.exe) в папке: %ProgramFiles(x86)%\Microsoft Visual Studio\Installer или %ProgramFiles%\Microsoft Visual Studio\Installer.
В файле конфигурации проверьте, присутствует ли следующий код; если код отсутствует, добавьте его перед последней строкой .
Ошибка: "Используемое соединение было закрыто"
Базовое соединение закрыто: непредвиденная ошибка при передаче
Visual Studio использует протокол TLS 1.2 для подключения к сетевым ресурсам. Устройства для обеспечения безопасности в частных сетях блокируют определенные подключения к серверу, если Visual Studio использует TLS 1.2.
Устранение этой ошибки подключения
Включите возможность подключения для следующих URL-адресов:
cdn.vsassets.io (размещение сети доставки содержимого или CDN)
*.gallerycdn.vsassets.io (размещает расширение Azure DevOps Services)
Частные URL-адреса серверов NuGet могут быть не включены в этот список. Используемые вами серверы NuGet можно посмотреть в файле %APPData%\Nuget\NuGet.Config.
Ошибка: "Не удалось проанализировать идентификатор из родительского процесса"
Причины возникновения этой ошибки: Подключенный сетевой диск или общий ресурс UNC связан с маркером доступа пользователя. При включении UAC создаются два маркера доступа пользователя: один с правами администратора и один без прав администратора. При создании сетевого диска или общего ресурса с ним связывается текущий маркер доступа пользователя. Поскольку начальный загрузчик следует запускать от имени администратора, он не сможет получить доступ к сетевому диску или общему ресурсу, если диск или общая папка не связаны с маркером доступа пользователя, который имеет права администратора.
Устранение этой ошибки
Можно использовать команду net use или изменить параметр групповой политики UAC. Дополнительные сведения об этих обходных путях и их реализации см. в следующих статьях службы поддержки Майкрософт:
-
(Подключенные диски недоступны в приглашении с повышенными привилегиями при настройке UAC на "запрос учетных данных" в Windows) (Программам не удается получить доступ к некоторым сетевым расположениям после включения контроля учетных записей пользователей в операционных системах Windows)
Поддержка или устранение неполадок
Иногда возникают проблемы. Если установить Visual Studio не удается, воспользуйтесь пошаговыми указаниями в статье Устранение неполадок при установке и обновлении Visual Studio.
I attempted to run my web service through visual studio. I faced an issue like :
So, I tried to stop and start the service manually. But the End process is disabled. It will be helpful if anyone could help with this issue
29 Answers 29
I had a similar issue when trying to run a project from Visual Studio 2019 on Windows 10. The application could not start because the port was apparently being used by another process. However, the netstat command showed that the port was not being used by any application.
After spending 2-days Googling I found a solution that worked for me. The port I was trying to use was in the excluded port range which you can see by running the command:
The culprits that reserved these ports in my case were Docker for Windows and Hyper-V
The Solution
I uninstalled Docker (as I did not need it) and disabled Hyper-V. To disable Hyper-V: Go to: Control Panel-> Programs and Features-> Turn Windows features on or off. Untick Hyper-V and restart the computer.
After the restart the command netsh interface ipv4 show excludedportrange protocol=tcp showed no ports reserved.
I then added the port for my application to the excluded port range by running the following command from an elevated command line:
Then I reenabled Hyper-V (Docker can be reinstalled if needed) and restarted the computer again.
Hyper-V now reserved its ports without interfering with the port used by my application: Reserved Port Ranges
This worked for me, except I need Docker so I just disabled it on start up instead of uninstalling it.
Like @Cory I changed my port in vs to be something outside the ranges, annoy because now i have to change referencing apps every time i do this but better than a full restart.
Error code 0x80070020 means ERROR_SHARING_VIOLATION , which in the case of IIS Express (or IIS) means that the port that it is attempting to listen on is being used by another process.
Use the netstat command to find out which application is using the port.
The a parameter tells netstat to display all connections and listening ports.
The o parameter tells netstat to display the process ID associated with the connection.
Running the above netstat command will produce output such as:
The last number displayed (9544 here) is the process ID.
This can be made considerably faster with the -n switch as well -- it uses "numeric" output, which means it doesn't waste time querying DNS in order to resolve IP addresses into hostnames.
I just wanted to mention for others that this didn't find anything using the port but changing the port localhost ran on did fix the issue. So if all else fails, just change it anyways.
I ran taskkill /PID 4 /F from a PowerShell window that was run as administrator and I got an error message 'Access denied'
Solution that worked from me is,
To fix this you must temporarily disable the winnat service, this is simply done by running this command (must be run as administrator)
net stop winnat
Start your docker services and start winnat again
net start winnat
I had the same problem. I just restarted Visual Studio and it worked.
In my case, my Windows 10 box blue-screened, and I had to reboot twice. Other web site projects worked fine (different local port), and none of the other answers here worked. Changing the port for the project didn't fix it either. There must be some other config in IIS Express itself.
It seems like this happens to me whenever I run a project in VS 2019 with debugging using F5, then later try to run it without debugging using Ctrl+F5 which is when it fails. A restart fixes it, though I wish I could actually prevent it from happening in the first place.
I had the same Issue. As @Kautsky Lozano mentions above Another application is using that port.
So [for a Windows OS] just:
- Open Resource Monitor (Task Manager -> Performance -> Open Resource Monitor )
- Click on the Network tab.
- And at TCP Connections find the application that uses the Local Port that IIS Express uses and close it. (it was firefox on my case)
If netstat doesn't show anything already using the port
netstat -ano | findstr
The port might be excluded, try this command to see if the range is blocked by something else:
netsh interface ipv4 show excludedportrange protocol=tcp
You can try to unblock the range from the start port for a number of ports (need Command Prompt with Administrator):
netsh int ip delete excludedportrange protocol=tcp numberofports= startport=
For me I couldn't unblock these, I just got "Access is denied", so I ended up having to pick another port for my site.
Nothing else but this helped. I could see the range included my port number netsh interface ipv4 show excludedportrange protocol=tcp . Lot of time was wasted until I found this to get it resolved. Thanks lot @john Leonard
After updating Windows 10 and/or Visual Studio 16+ it might happen due to an internal bug that IISExpress fails to register any development website because it no longer accepts localhost connections.
To fix the issue, you just have to register again the binding. To do so, run from an administrative shell the following command:
I ran into the same problem after we had upgraded a solution from Visual Studio 2012 to 2015. I had come here and ran netstat only to find that no other application was using the same ports. It turns out I had the same sites with the same ports mapped in the applicationhost.config at Users//Documents/IISExpress/config and the applicationhost.config in the .vs folder inside my solution. I should note that the problem didn't start right after the upgrade either. It just start failing consistently one morning. A couple reboots didn't seem to solve the problem either.
Removing the conflicted sites from the one stored in my Documents and restarting Visual Studio solved the problem.
- Go to Task Manager
- Search for "Application Frame Host" Process
- End this Process
- Try to Run Again
If not successful, Try run this command in cmd: "net stop winnat"
This Answer Work For Me
1-open cmd with Run As Administrator
2-type net stop winnat
you got
"The Windows NAT Driver service was stopped successfully."
3- then type net start winnat
you got
The Windows NAT Driver service was started successfully.
after that go to visual studio and press ctrl+f5
In my case, doing the following did the trick:
- Delete the Site from .vs\\config\applicationhost.config
- Delete the Site from Documents\IISExpress\config\applicationhost.config
- Delete the IISUrl from the .csproj
When I restarted Visual Studio, it assigned the project a completely new port number and ran perfectly
deleting iisExpress which includes applicationUrl and sslport from launchsettings.json did it for me with the other steps.
I just had this issue even though netstat did not show any conflicts.
The following fixed it for me:
This indeed happened after installing Docker .
Steps to Resolve:
Checked Network under Resource Monitor :
- Port 66666 was not being used by any network process.
Tried to Quit Docker Desktop :
Checked excluded port range: netsh interface ipv4 show excludedportrange protocol=tcp
Try to Untick Hyper-V in Turn Windows Features On and Off :
- Cannot Find Hyper-V in Turn Windows Features On and Off .
Attempted to remove Port from the Exclusion Ranges:
netsh int ipv4 add excludedportrange protocol=tcp startport=66666 numberofports=1 store=persistent
Inspired by this link to attempt to restart network services:
- net stop winnat
- after running this command, confirmed port 66666 already disappeared from Exclusion Ranges by running netsh interface ipv4 show excludedportrange protocol=tcp
- stopped other network services just to be more assured
- net stop LanmanWorkstation
- net stop WlanSvc
- net stop WwanSvc
- restart the network services
- net start WwanSvc
- net start WlanSvc
- net start LanmanWorkstation
- net start winnat
Confirmed unavailable port is available now:
- netsh interface ipv4 show excludedportrange protocol=tcp
- Port 66666 no longer in the Exclusion Ranges
- IIS Express Web Server can be launched successfully.
Launched Docker Again:
Hope this helps anyone.
I had this problem when upgrading an MVC project. I copied over the newer-MVC .csproj over my existing .csproj file then worked back to a fully working Project. What I failed to consider is the existing port number in the old .csproj. The new project had a new port number, yet shared the Project/Assembly Name. That was enough to make IIS Express lose its mind and throw this exception.
Just digging the old port number out of git and changing the IIS Express URL to include it in Project Settings was enough to fix it.
- Close visual studio
- delete ".vs" folder
- Try change port "localhost:8080"
It worked for me.
Reason for this error that is you give the wrong port number to your application.
use the port near to 8080 number, i.e:
to change the port for you application in visual-Studio
The easiest first pass at this without getting into the command console is to just shut down all applications (including VS), then launch VS by itself and try it again. There is likely another application like your browser causing the conflict. In my case Chrome caused it and was solved when shutting everything down and restarting VS. I opened Chrome again and everything was fine.
The netstat stuff above is useful, but to me that's only if you can't do what I'm suggesting.
it returns: TCP 0.0.0.0:443 pe01:0 LISTENING 2904 The last number (thanks to @chris-schiffhauer) is PID to kill. Go to the Task Manager -> Processes -> [Show Processes From All users], Kill a process with PID=2904. In my case, it was VmWare host.
Either change 433 to something else, like 4330 or delete the conflicting tag.
I was able fix this problem by removing everything from
Port numbers do not match
In my case the problem was in my Bindings Tags found in the config file in .vs under my solution folder, the port numbers did not match. The bindings were as follows
So what i did was to delete inside binding and run my web app, then it generated new binding with a different number then i copied the new generated port to my settings, then the error went away.
If your solution contains a plain old fashioned website (not a web application) then the port numbers are also in the solution file .sln
Having just wasted half a day trying to fix this same issue, I felt I should add the solution which eventually worked for me.
TL;DR If netstat indicates that the problematic isn't in use, still try a few others in a totally different range
I've run into this problem before but usually find restarting visual studio, changing ports (increment by 1) or rebooting do the trick. However on this occasion none of this helped, and netstat wasn't finding a conflicting process. I even reinstalled IIS and visual studio and removed several other programs which I suspected could be interfering. It seemed as though IIS was trying to launch multiple instances of the same site.
Eventually I tried running netstat without findstr . I visually scanned the list of active ports and noticed that although the ones I had tried were not listed, there were a few processes using ports in a similar range. So instead I looked for a range which was free, picked a port number and that seems to now be working.
При публикации веб-приложения из Visual Studio разработчик может столкнуться с некоторыми проблемами, и не всегда текст ошибки может помочь избавиться от проблем и правильно настроить сервер.
Ниже я опишу наиболее распространенные из них.
Надеюсь, что данная статья поможет сэкономить время, большое количество которого я потратил при изучении проблем.
Давайте попробуем развернуть приложение на чистый сервер Windows 2008 R2, на котором установлена роль «Web Server (IIS)».
1. Для этого в Visual Studio (у меня Visual Studio 2012 Professional) кликаем правой мышкой на проекте и выбираем пункт меню «Publish. »
Откроется окно мастера публикации, в котором нужно создать профиль
Вводим имя профиля (я назвал профиль также, как называется мой веб-сервер — «app10») и нажимаем кнопку «ОК».
Затем заполняем поля ввода и нажимаем кнопку «Validate Connection».
И тут начинается самое интересное.
2. Валидация завершилась с ошибкой.
Для того, чтобы посмотреть текст ошибки, нужно щелкнуть на гиперссылке «Failed (click for details)»
3. Первая ошибка:
Could not connect to the destination computer ("app10"). On the remote computer, make sure that Web Deploy is installed and that the required process ("The Web Management Service") is started.)
Студия не получила ответа от сервера.
Необходимо проверить настройки веб-сервера (в моем случае он имеет доменное имя «app10»), для чего необходимо зайти в Server Manager (у меня на сервере установлена англоязычная версия Windows 2008 R2, поэтому я буду писать английский наименования пунктов меню и заголовков окон).
4. Откройте диспетчер служб IIS и выберите узел с именем машины:
Я скрыл имя пользователя на скриншоте.
5. В разделе «Management» нужно проверить наличие пунктов «IIS Manager Permissions», «IIS Manager Users» и «Management Service».
У меня их нет, поэтому нужно установить.
Для этого щелкните правой мышкой на пункт «Web Server (IIS)» в левой части окна «Server Manager» и выберите пункт «Add Role Services».
Откроется окно выбора роли.
В разделе «Management Tools» отметьте пункт «Management Service» и нажмите кнопку «Next».
В следующем окне мастера добавления роли нажмите кнопку «Install».
Необходимо дождаться окончания процесса добавления роли и убедиться, что все прошло успешно:
Закрываем окно добавления роли и опять переходим к разделу «Management» (см. пункт 5).
Необходимые нам пункты появились.
6. Необходимо проверить, что Брендмауэр Windows не мешает установлению соединения.
Для этого откройте оснастку «Windows Firewall with Advanced Security», которая находится в меню «Пуск» — «Administrative Tools».
Необходимо убедиться, что входящие соединения на порт 8172 разрешены.
(У меня брендмауэр вообще отключен).
7. Необходимо убедиться, что Web Management Service слушает порт 8172.
Для этого откройте в настройках сервера дважды щелкните мышкой по пункту «Management Service»
В открывшемся окне проверьте, что указан порт 8172, а также разрешите удаленные подключения, установив галочку «Enable remote connection».
Если не поставить эту галочку, то в мастере публикации в Visual Studio будет возникать ошибка:
Could not connect to the remote computer ("app10") using the specified process ("The Web Management Service") because the server did not respond. Make sure that the process ("The Web Management Service") is started on the destination computer. The remote server returned an error: (403) Forbidden.
Теперь нажмите кнопку «Apply» с зеленой галочкой в правой части окна надстроек.
После применения настроек нажмите там же кнопку «Start», что приведет к запуску службы.
8. Переключаемся в Visual Studio и снова нажимаем кнопку «Validate Connection» в мастере публикации.
У меня открылась ошибка сертификата, но ее можно просто игнорировать и нажать кнопку «Accept», предварительно поставив галочку «Save this certificate for future sessions of Visual Studio».
9. После этого у меня возникла ошибка 404:
Could not connect to the remote computer ("app10"). On the destination computer, make sure that Web Deploy is installed and that the required process ("The Web Management Service") is started. The remote server returned an error: (404) Not Found.
Необходимо убедиться, что установлен инструмент «Microsoft Web Deploy 2.0».
Для этого пройдите в «Пуск» — «Control Panel» — «Programs and Features» и проверьте наличие установленного продукта «Microsoft Web Deploy 2.0».
Если его нет, то скачайте его отсюда и установите на сервере.
Во время установки нужно выбрать тип установки «Custom» и выбрать для установки все пункты, предлагаемые инсталлятором:
После чего обновите окно «Programs and Features» и он у вас появится.
10. После установки «Microsoft Web Deploy 2.0» необходимо перезапустить службу «Web Management Service».
Теперь нажимаем кнопку «Validate Connection» в мастере публикации в Visual Studio и ВУАЛЯ.
Проверка успешно пройдена.
Нажимаем кнопку «Next» дважды и публикуем приложение на веб-сервер, нажав кнопку «Publish».
UPDATE 03.08.2015
Если во время проверки соединения с сервером (при нажатии на кнопку «Validate Connection») возникает ошибка:
Could not complete an operation with the specified provider ("contentPath") when connecting using the Web Management Service.
необходимо в диспетчере служб IIS выбрать узел с именем машины и дважды кликнуть левой клавишей мыши на пункте «Management Service Delegation»:
Для устранения данной проблемы необходимо еще раз запустить инсталлер WebDeploy, выбрать пункт «Change» и доустановить компоненты.
Затем перезапускаем оснастку управления сервером и данный пункт появится.
В открывшемся окне необходимо добавить новое правило, нажав в правой верхней части на ссылку «Add Rule. » и выбрав пункт «Deploy Applications with Content» и нажав кнопку «ОК»:
В открывшемся окне необходимо указать пользователя, учетные данные которого вы используете для публикации из Visual Studio:
А также в выпадающем меню Providers необходимо дополнительно выбрать пункты «createApp» и «setAcl»:
После нажатия кнопки «ОК» откроется окно добавления пользователя.
Здесь в поле «Name» можно поставить * и нажать кнопку ОК:
После выполнения данных действий, окно правил «Management Service Delegation» будет иметь следующий вид:
И описанная ошибка исчезнет.
UPDATE 19.01.2017
Если во время проверки соединения с сервером (при нажатии на кнопку «Validate Connection») возникает ошибка:
Could not connect to the remote computer ("serverName") using the specified process ("Web Management Service") because the server did not respond. Make sure that the process ("Web Management Service") is started on the remote computer.
а в конце текста ошибки написано «The remote server returned an error: (550)».
Это говорит о том, что вы опечатались в параметре «Site name» в окне настроек публикации.
Проверьте имя сайта и сравните его с тем, куда публикуете своё приложение.
В этом руководстве мы настроим Web Deploy в среде Windows Server 2008 R2 для простого развертывания приложений из Visual Studio 1 кликом мыши. Web Deploy позволяет настроить публикацию пользователем, не обладающим правами администратора.
Установка Web Deploy
Web Deploy можно установить двумя способами (мне именно так и пришлось).
Web Platform Installer
Первый способ через Web Platform Installer. Его необходимо скачать и установить на сервер. Затем открыть и выбрать такие пункты как: Web Deploy, Web Deploy for Hosting Servers и IIS Recommendated Configuration (на скриншоте не видно)
Пакеты, устанавливаемые через WPI включают в себя дополнительные компоненты, некоторым может это не понравится. Однако для новчиков этот путь будет самый простой.
Установка через msi
Необходимо скачать файл установки Web Deploy (на сегодня версии 3.5) и установить его. При ручной установке необходимо будет вручную установить необходимые службы IIS. Делается это через панель управления сервером: Roles > IIS > Add Role Services
- Logging Tools
- Management Service (IIS Management Console может понадобиться)
Настройка сайта для удаленной публикации
После всех дейсвий должен был появиться пункт меню
Создаем пользователя не администратора и задаем ему сложный пароль. Также даем ему права на запись в папку сайта в wwwroot.
Далее настраиваем удаленную публикацию:
- Выбираем пользователя, с которым мы будем публиковать наш сайт;
- Указываем URL для публикации. Это должен быть внешний IP сервера с открытым портом по умолчанию 8172. При установке через WPI создается правило в Firewall и порт открывается.
- Указываем место, куда сохранить файл настроек.
- Нажимаем Setup
- Служба msdepsvc запущена в автозапуске и работает сейчас net stop msdepsvc & net start msdepsvc
- Аналогично служба wmsvc net stop wmsvc & net start wmsvc
- Также необходимо уточнить, возможен ли пинг до 80 порта (для службы Web Deployment Agent Service (MsDepSvc)) и 8172 для службы Web Management Service (WmSvc, handler).
Настройка публикации Web Deploy в Visual Studio
После успешной настройки на стороне сервера необходимо настроить публикацию в Visual Studio. Для этого создаем профиль публикации, в методе публикации выбираем Web Deploy.
На следующем шаге выбираем конфигурацию Release. Здесь же можно указать строку подключения, на которую заменит VS при публикации (не пробовал). Получится удобная публикация решения в 1 клик:
Важно: название сайта должно быть таким же как оно отображается в IIS Management.
Важно: Если вы установили подписанный сертификат SSL на удаленном сервере, убедитесь, что вы установите флажок “Разрешить ненадежный сертификат” флажок. По умолчанию Web Deploy установит сертификат для вас, чтобы он был уникальный, однако он будет самоподписанный.
Также есть настройка, которая позволяет уточнить «Оставлять ли лишние файлы или нет». Веб деплой будет копировать только изменившиеся файлы с момента последней публикации.
Резюме
Читайте также: