Файл проекта неполон отсутствует ожидаемый оператор imports
When loading the Blazor.SLN in VS I get this error:
C:\sources\Blazor\samples\MonoSanityClient\MonoSanityClient.csproj : error : Project file is incomplete. Expected imports are missing.
Am I missing something? :-)
Thanks.
The text was updated successfully, but these errors were encountered:
32 Answers 32
I had the same issue. In my case, deleting global.json and appsettings solved the problem.
This worked for me although to clarify I just had to delete (/rename) "global.json". Fwiw: It contained: < "sdk": < "version": "2.0.0" >>
dotnet --version shows 2.1.201, while global.json mentioned a slightly lower version, 2.1.101. Apparently the version has to match exactly for it to work, no downwards compatibility. Or just remove the file as suggested in this answer.
You can check global.json file which you can find in solution root directory and make sure that the target SDK version in it installed on your machine or update it to one you already have it installed for example if you have SDK version 2.1.4 installed your global.json should look like this
This was it for me. Version "2.1.300" in global.json , but 2.1.200 & 2.1.403 installed; changing to 2.1.400 worked.
Worked for me as well. Changed the version to match the closest to what I already had on my system. You can run "dotnet --versions" to see what you have installed.
dotnet --list-sdks and dotnet --list-runtimes to see all you have installed dotnet --version will show the current version in use.
This was the solution for us as well. In our case, we had some projects on VS2017 with netcore 2.1; we installed netcore 3, and we could not open the projects any more. Creating global.json in the project's root folder solved the issue
Even after uninstalling certain version from control panel, there would the files and folders with deleted version found in C:\Program Files\dotnet\sdk
Please go and delete unwanted version folder
Repairing last Core installation worked for me
For people looking "how" to repair the .NET Framework (works for Core too), search for ".NET Framework Repair Tool" in your favorite search engine. Running just the first step fixed it for me.
In my case, I had two versions of Visual Studio installed (15.7 and 15.6). 15.7 didn't have the web workloads installed, though .net core 2.1 RC1 was already installed. I installed the asp.net workload into VS2017, and then repaired my .net core install for good measure. Definitely something in this process swapped my c:\program files(x86)\dotnet and c"\program files\dotnet in this path and Visual Studio (15.7) wouldn't open my web project.
I simply edited the System Environment variables, moved the x86 folder down one and voila - reopened Visual Studio and it now loaded my project.
Installed NET4.7.1, then all existing Net.Core projects became ruined. The "Move down" magic fixed them back.
"Project file is incomplete. Expected imports are missing"
The solution was to use Visual Studio not SSDT, see in Help > About:
I solved this problem by modifying the first line in the .csproj file from:
I have solved this problem a couple of times lately by closing Visual Studio and running the following commands
- dotnet nuget locals -c all
- dotnet clean
- dotnet build
There seems to be times, especially at the beginning of projects, when nuget gets out of whack (technical term).
Later after upgrading VS2019 to the latest release I started to have the same errors and had to upgrade VS2017 again.
I started to get this error when unistalled all my old .NET Core SDKs and installed the latest one, 2.1.5 at the time of posting. I have tried all the solutions here without any luck so decided to check what is the current SDK version after all the cleaup I did because I thought this is causing the problem, and I was right - started a command prompt and wrote dotnet --version and got the message "Did you mean to run dotnet SDK commands? Please install dotnet SDK from:". Strange, the SDK is installed but the system doesn't see it. Then I looked in my environment variables and the PATH variable had the x86 for dotnet path before the regular Program Files (the x64 one) path. So I moved the x64 before the x86 and voila, everthing is back to normal.
Hope I helped someone.
You helped me. This just happened when I upgraded from 2.2.3 to 2.2.4. I wonder if there's a specific order of install new/uninstall old that causes it to happen.
@MattOG, I have tried numerous variants for installing/uninstalling but this problem occurs every time. I guess will just have to get used to that ;) It's not a biggy after all when we have a source like stackoverflow.
Но когда я создаю новое приложение ядра asp, VS не удалось с ошибкой
«Файл проекта не завершен. Ожидаемый импорт отсутствует»
Пожалуйста, кто-нибудь может помочь?
Даже после удаления определенной версии с панели управления в C: \ Program Files \ dotnet \ sdk будут файлы и папки с удаленной версией.
Пожалуйста, перейдите и удалите папку с нежелательной версией
Я была такая же проблема. В моем случае проблема была решена удалением global.json и appsettings.
Это сработало для меня, хотя, чтобы уточнить, мне просто пришлось удалить (/ переименовать) «global.json». Fwiw: Он содержал: <"sdk": <"version": "2.0.0">>"sdk":>
dotnet --version показывает 2.1.201, а global.json упомянул немного более низкую версию 2.1.101. Очевидно, версия должна точно соответствовать, чтобы она работала, без обратной совместимости. Или просто удалите файл, как предлагается в этом ответе.
Большое спасибо! Это работает! SDK 2.2.105 работает только с Visual Studio 15.9.8 или более ранней версии.
Вы можете проверить файл global.json, который вы можете найти в корневом каталоге решения, и убедиться, что целевая версия SDK в нем установлена на вашем компьютере, или обновить его до той, которая у вас уже установлена, например, если у вас установлена версия SDK 2.1.4. ваш global.json должен выглядеть так
Это было для меня. Версия "2.1.300" global.json , но 2.1.200 & 2.1.403 установлена; переход на 2.1.400 работал.
Сработало как изменение его на одну из установленных версий SDK, так и version полное удаление атрибута
У меня тоже сработало. Изменил версию, чтобы она соответствовала наиболее близкой к той, что у меня уже была в моей системе. Вы можете запустить «dotnet --versions», чтобы увидеть, что вы установили.
dotnet --list-sdks и dotnet --list-runtimes чтобы увидеть все, что вы установили, dotnet --version будет показана текущая используемая версия.
Это было решением и для нас. В нашем случае у нас было несколько проектов на VS2017 с netcore 2.1; мы установили netcore 3, и больше не могли открывать проекты. Создание global.json в корневой папке проекта решило проблему
Восстановление последней установки Core сработало для меня
В моем случае у меня было установлено две версии Visual Studio (15.7 и 15.6). В версии 15.7 не было установленных веб-нагрузок, хотя .net core 2.1 RC1 уже был установлен. Я установил рабочую нагрузку asp.net в VS2017, а затем исправил установку ядра .net для хорошей меры. Определенно что-то в этом процессе поменяло местами мои c: \ program files (x86) \ dotnet и c "\ program files \ dotnet по этому пути, и Visual Studio (15.7) не открыла бы мой веб-проект.
Я просто отредактировал переменные системной среды, переместил папку x86 на одну вниз и, вуаля, снова открыл Visual Studio, и теперь она загрузила мой проект.
Установил NET4.7.1, потом все существующие проекты Net.Core рухнули. Магия «Двигаться вниз» вернула их обратно.
«Файл проекта не завершен. Ожидаемый импорт отсутствует»
Решением было использовать Visual Studio, а не SSDT , см. Help> About:
В последнее время я решил эту проблему пару раз, закрыв Visual Studio и выполнив следующие команды
- dotnet nuget locals -c все
- dotnet clean
- сборка dotnet
Кажется, бывают моменты, особенно в начале проекта, когда nuget выходит из строя (технический термин).
Я решил эту проблему, изменив первую строку в файле .csproj:
Позже, после обновления VS2019 до последней версии, у меня начались те же ошибки, и мне пришлось снова обновить VS2017.
Надеюсь, я кому-то помог.
Ты мне помог. Это только что произошло, когда я обновился с 2.2.3 до 2.2.4. Интересно, есть ли определенный порядок установки нового / удаления старого, который вызывает это.
@MattOG, я перепробовал множество вариантов установки / удаления, но эта проблема возникает каждый раз. Думаю, к этому нужно просто привыкнуть;) В конце концов, это не так уж и важно, когда у нас есть такой источник, как stackoverflow.
Все пакеты уже установлены и восстанавливать нечего.
но эти 52 ошибки все еще есть, и в разделе Инструменты -> Диспетчер пакетов NuGet -> Управление пакетами NuGet для решения на этом решении ничего не установлено, также я недавно обновил свой VS2017 до 15.5.4
Вы дали согласие на восстановление NuGet? Перейдите к инструментам, параметрам, найдите NuGet и установите флажок «Разрешить NuGet . ».
Если кто-то работает на Mac, у нас была эта проблема, и мы устранили ее, удалив пробелы в пути к хранилищу (который был создан во время git pull): Мой% 20Project становится MyProject.
Ошибка возникает из-за того, что dotnet cli изначально не создает все необходимые файлы. Выполнение восстановления dotnet добавляет необходимые файлы.
Это было также исправлением для сервера сборки. Добавлен шаг командной строки для запуска «восстановления dotnet» после обычного восстановления NuGet.
Решение @ Der_Meister по добавлению опции / t: Restore сработало для меня, однако мне пришлось построить решение дважды (два отдельных этапа сборки). Сначала с параметром / t: Restore, а затем снова без него.
В моем случае ошибка была в GIT-хранилище. В названии были пробелы, поэтому мой проект не удалось восстановить
Если это ваша проблема, просто переименуйте репозиторий GIT при клонировании
Я подумал про себя, что это не может быть. Попробовав еще один час с другими предлагаемыми решениями, я наконец испытал это от отчаяния, и это решило мою проблему. Черт возьми!
в моем случае я просто переименовал свою физическую папку, удалив% 20 и заменив ее обычным пространством, и все работает хорошо
В случае, если «восстановление dotnet» не работает, могут помочь следующие шаги:
- Visual Studio >> Инструменты >> Параметры >> Диспетчер Nuget >> Источники пакетов
- Не проверены любые сторонние источники пакетов.
- Восстановить решение.
Закрытие и повторное открытие Visual Studio решило эту проблему для меня, как только я убедился, что пакеты NuGet были восстановлены, как и другие ответы, опубликованные здесь.
Изменить: В некоторых случаях мне приходилось перезапускать Visual Studio сразу после другого перезапуска, поэтому не думайте, что перезапуск не поможет только потому, что вы недавно перезапустили.
У меня были некоторые проблемы с подключением в моей рабочей локальной сети, которые мешали NuGet. Перезагрузка моего ПК решила проблему!
Это на самом деле не ответ , потому что иногда вы используете CLI инструменты get и build и вы не раскрываем VS. Я знаю, почему он работает с VS - потому что VS автоматически разрешает зависимости проекта.
@TS вопрос с тегом «Visual Studio 2017 года», так что я бы сказал , что это является ответом. Вы поднимаете интересный момент, однако, что проблема заключается в разрешении VS-зависимостей. Если у вас есть больше информации о том, что идет не так, я уверен, что это будет интересно читать
Добавьте /t:Restore к своим MSBuild Аргументы в Build Solution.
Для меня, когда я сделал - dotnet restore все еще ошибка происходила.
1 Инструмент -> Менеджер пакетов NuGet -> Настройки диспетчера пакетов -> нажмите «Очистить в Nuget Catche (s)»
2 dotnet восстановление
Я собираюсь попробовать это в следующий раз, когда это произойдет. Это может быть лучший подход , чем мой (закрыть и снова открыть VS) , который обычно занимает возраст для меня.
В visual studio 2017, пожалуйста, выполните следующие действия:
1) выберите Tool => Options => NuGet Package Manager => Источники пакетов, затем снимите флажок Microsoft Visual Studio Offline Packages Option.
2) Теперь откройте Tool => NuGet Package Maneger => Консоль диспетчера пакетов. 3) выполнить команду в PM> dotnet restore.
Надеюсь, что это работает .
Выберите Инструменты > Диспетчер пакетов NuGet > Консоль диспетчера пакетов.
А затем запустить:
немного поздно для ответа, но, кажется, это добавит ценность. Глядя на ошибку - кажется, это происходит в конвейере CI / CD.
Достаточно просто запустить «сборку dotnet».
DotNet build выполняет «восстановление» по умолчанию.
Ничто из вышеперечисленного не помогло мне. Но простое удаление всех папок bin и obj помогло.
Эта проблема произошла для меня, когда я работал над Dockerfile. удаление этих папок привело к правильной работе dotnet-восстановления в контейнере.
Решается добавлением / t: Restore; Build to MSBuild Аргументы
При использовании VSTS проверьте файл global.json. Я ввел версию SDK как просто «2.2», что вызвало ошибку разбора (но не при локальной сборке). Добавление полной версии «2.2.104» решило проблему.
Я потерял несколько часов из-за этой ошибки в DevOps Azure, когда установил задачу Visual Studio Build в конвейере сборки, чтобы построить отдельный проект в моем решении, а не в целом решении.
Это означает, что DevOps либо не создает ни один (или, возможно, некоторые, я не уверен, какой) из проектов, на которые ссылается проект, на который вы нацелены для сборки, и, следовательно, эти проекты не будут иметь свой project.json. сгенерированные файлы .asset, которые затем вызывают эту проблему.
Решением для меня было переключиться с использования задачи VS Build на задачу MSBuild. Использование задачи MSBuild для отдельного проекта правильно создает все проекты, на которые ссылается создаваемый вами проект, и устраняет эту ошибку.
Если эта ошибка возникает как часть сборки в Azure DevOps (TFS), и ваша сборка уже имеет задачу восстановления NuGet , эта ошибка может указывать на то, что задача восстановления NuGet не смогла восстановить все пакеты, особенно если вы используете собственный источник пакета ( такой как внутренний сервер NuGet). Добавление /t:Restore;Build к аргументам MSBuild, кажется, является одним из способов устранения ошибки, но при этом MSBuild просит выполнить дополнительную операцию восстановления NuGet. Я считаю, что это успешно, потому что MSBuild использует пользовательский источник пакета, настроенный в Visual Studio. Предпочтительным решением является исправление задачи восстановления NuGet.
Чтобы настроить собственный источник пакета для задачи восстановления NuGet:
Using VS 2017 and trying to test the samples. Have tried both the web-application and csharp-php-hybrid apps, but both of them give the following error when opened:
"Project file is incomplete. Expected imports are missing"
Do I need to install something first or what am I missing here?
The text was updated successfully, but these errors were encountered:
jakubmisek commented May 9, 2018
Rick-Anderson commented Mar 22, 2018
@ChristianWeyer This is not Blazor related. I'm working on this problem and will update this issue with a new GitHub issue. See this link for another customer that hit this error.
cc @barrytang
jakubmisek commented Sep 6, 2018
VoodooSV commented Aug 29, 2018
AlanJacobsSandnet
global.json is in the solution directory
AlanJacobsSandnet commented Aug 29, 2018
@urielgoncalves: where will I find the global.json file on my machine?
hexarcate commented May 7, 2018 •
ShadowDancer commented Aug 16, 2018
I have two pcs with VS where blazor templates fail, however on third everything works.
Everything is updated and repair does not help.
AlanJacobsSandnet commented Mar 23, 2018
I am getting something very similar when trying to create any ASP.NET Core project from in VS2017 (v15.6.3). VS creates a project file but fails to load it successfully reporting "Project file is incomplete. Expected imports are missing" in a popup message. The contents of the project file for a new ASP.NET Core Web Application project are as follows:
This was first reported through the Razor pages tutorial as mentioned above by Rick Anderson - see this link
Alan Jacobs
ChristianWeyer commented Mar 16, 2018
I am now running on VS 2017 15.7 Preview 1 and followed the steps for 'If you're working on Blazor.sln. '.
Still for Blazor.sln I get this.
C:\sources\Blazor\samples\MonoSanityClient\MonoSanityClient.csproj : error : Project file is incomplete. Expected imports are missing.
AlanJacobsSandnet commented Aug 30, 2018
How did you " install ASP.Net Core SDK from Microsoft 2.1.4"? Using the Visual Studio Installer, or by some other process?
rynowak commented Apr 4, 2018
I've seen this happen when using old SDKs that don't have the corresponding runtime installed, or using SDKs without the NuGet restorer.
rynowak commented Apr 10, 2018
davkean commented Apr 4, 2018 •
I can imagine this happens when;
Rick-Anderson commented Mar 23, 2018
@ChristianWeyer can you verify the following file was installed?
AlanJacobsSandnet commented Apr 7, 2018
urielgoncalves commented Aug 22, 2018 •
ChristianWeyer commented Mar 16, 2018
Thanks mate, will check this out.
eloekset commented Aug 8, 2018
SteveSandersonMS commented Mar 16, 2018
I'll mark this as closed since I think it's OK, but please let me know and/or reopen if there still appears to be a problem later.
bradphelan commented Apr 3, 2018 •
Not specific to do with blazor but the same error nonetheless
I also have C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\Managed\GeneralBrowserObject.xaml installed but am seeing the same issue.
Funny thing is that the project build via msbuild at the command line.
gordon-matt commented Mar 1, 2018
I've just updated VS and it still had the same error. I then tried dotnet restore and that seems to have fixed it, thanks.
bradphelan commented Apr 3, 2018
I did a repair on the install of Visual Studio ( All is now well :) ) Maybe that helps you too.
DaveMagrathSmith commented Sep 6, 2018
Thanks, Jakub. I had forgotten to run dotnet restore on the sample application, and that did fix the problem there.
However, I am still unable to open new projects created locally. For example:
C:\Projects\PHPLibTest>dotnet new classlib -lang PHP
The template "Class library" was created successfully.
Everything looks good, but when I try to open in visual studio, I get the "Project file is incomplete. Expected imports are missing" error. I wonder if there is something wrong with the template? Having trouble figuring out what could be going wrong, but I'll keep digging.
Rick-Anderson commented Apr 10, 2018
That would be the issue then! Blazor requires the newest preview of the dotnet CLI
I've got several customers getting this error creating Razor Pages projects.
rynowak commented Apr 10, 2018
davkean commented Apr 4, 2018 •
Is everyone whom is having this trouble using MSBuild.Sdk.Extra? // cc @onovotny
Rick-Anderson commented Apr 12, 2018
@AlanJacobsSandnet It's not an easy migration from Web Forms to Razor Pages. Razor Pages have alot of advantages over Web Forms. You could try uninstalling/reinstalling VS.
rynowak commented Apr 9, 2018 •
@AlanJacobsSandnet - do you have dotnet on your %PATH% ?
If you do a dotnet --list-sdks at the command line, what does it output?
This kind of problem can occur if you have an older version on the path that is preventing a newer build from being used
AlanJacobsSandnet commented Apr 13, 2018
AlanJacobsSandnet commented Apr 10, 2018
Product Information:
Version: 2.1.200-preview-007474
Commit SHA-1 hash: 06ce7628d3
Runtime Environment:
OS Name: Windows
OS Version: 10.0.16299
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.200-preview-007474\
ChristianWeyer commented Apr 5, 2018
Sorry @Rick-Anderson - I was on vacation ;-)
Yes, \Enterprise\MSBuild\Microsoft\VisualStudio\Managed\GeneralBrowseObject.xaml is installed.
Rick-Anderson commented Mar 23, 2018
@ChristianWeyer and @AlanJacobsSandnet can you verify the following file was installed?
davkean commented Apr 4, 2018
ChristianWeyer commented Mar 16, 2018
Thanks mate, will check this out.
DaveMagrathSmith commented Sep 6, 2018 •
I'm getting the same error when trying to open PeachPie libraries in Visual Studio 2017 (15.8.2): "Project file is incomplete. Expected imports are missing". This happens even with the official 'php-library' sample.
This is my dotnet --info:
Runtime Environment:
OS Name: Windows
OS Version: 10.0.17134
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.401\
Host (useful for support):
Version: 2.1.3
Commit: 124038c13e
And here is the sample msbuildproj file (unmodified from GitHub):
Rick-Anderson commented Apr 4, 2018
@davkean I've had several customers including @AlanJacobsSandnet report it. They were creating a Razor Pages web app with VS. See this link
AlanJacobsSandnet commented Apr 12, 2018
Читайте также: