Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

huangapple go评论78阅读模式
英文:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

问题

我使用Visual Studio 2022创建了一个新项目,并选择了模板“ASP.NET Core Web App(Model-View-Controller)”,但创建的项目无法构建,出现以下错误:

错误 CS5001
程序不包含适用于入口点的静态 'Main' 方法

Program.cs

var builder = WebApplication.CreateBuilder(args);

// 将服务添加到容器中。
builder.Services.AddControllersWithViews();

var app = builder.Build();

// 配置HTTP请求管道。
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // 默认的HSTS值为30天。您可能需要根据生产情况更改此值,请参阅https://aka.ms/aspnetcore-hsts。
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

我尝试删除了Program.cs文件,但问题没有解决。我还尝试使用“ASP.NET Core Web App”模板创建项目,但问题仍然存在。

英文:

I created a new project using Visual Studio 2022 and selected the template "ASP.NET Core Web App (Model-View-Controller)" but the project created won't build and I get the following error:

> Error CS5001
> Program does not contain a static 'Main' method suitable for an entry point

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

I tried removing the Program.cs file which did not fix it. I also tried creating a project from the "ASP.NET Core Web App" template which had the same issue.

答案1

得分: 2

您正在使用旧版本的C#。

原因

在您的 Program.cs 中没有类定义,尽管C#是面向对象的,所有代码必须位于类内。

因此,编译器会自动生成一个名为 Program 的类,其中包含一个名为 Main 的方法,该方法接受类型为 string[]args 参数。您的代码将放在该方法中。这个概念被称为顶级语句

顶级语句首次出现在C# 9.0中。如果您使用较旧的版本,编译器将显示错误消息,因为它不知道如何处理没有类定义的代码。

如何修复

升级到C# 9或更高版本。这是解决方案。

如果由于某些原因您无法执行此操作,请自行创建一个类和一个 Main 方法:

using System;
// Using directives

namespace YourWebApp {
  public static class YourWebApp {
    public static void Main(string[] args) {
      // 您的 Program.cs 代码
    }
  }
}
英文:

You're using an old version of C#.

Reason

There's no class definition in your Program.cs, even though C# is object-oriented and all code must be inside classes.

Thus the compiler automatically generates a class called Program with a Main method inside, which takes an args argument of type string[]. Your code is put into that method. This concept is called top-level statements.

Top-level statements appeared in C# 9.0. If you're using an older version, the compiler will show an error message because it doesn't know how to handle code without class definition.

How to fix

Upgrade to C# 9 or higher. That's the solution.

If for some reasons you cannot do it, create a class and a Main method yourself:

using System;
// Using directives

namespace YourWebApp {
  public static class YourWebApp {
    public static void Main(string[] args) {
      // Your Program.cs code
    }
  }
}

答案2

得分: 2

我尝试删除Program.cs文件,但没有解决问题。我还尝试从“ASP.NET Core Web App”模板创建项目,但出现了相同的问题。

实际上,选择比默认版本更新的语言版本可能会导致难以诊断的编译时和运行时错误。最重要的是,最新的C#编译器会根据项目的目标框架确定默认的语言版本。

此外,Visual Studio没有提供更改该值的用户界面,但您可以通过编辑csproj文件来更改它。

导致问题的原因:

您遇到此问题可能是由于多种原因导致的。

首先,当框架和语言版本不匹配时,可能会导致此问题。每个.NET运行时版本的发布都有其兼容的语言版本。

让我们看看下表:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

注意:您可以参考此官方文档。

检查计算机上的运行时和语言版本:

另一个重要点是,检查计算机上的.NET运行时。您可以使用以下命令执行:

dotnet --list-sdks
dotnet --list-runtimes

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

注意:您可以在此处获取更多详细信息。

在Visual Studio中检查运行时和语言版本:

检查您的csproj文件中的值。您应该得到以下内容:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

在Visual Studio中检查框架版本:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

在Visual Studio中检查语言版本:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

注意:我在我的计算机上安装了.NET,并且使用的是Visual Studio 2022版本17.5.2。

输出:

如果您按照上述步骤创建MVC应用程序,假设使用.NET 6和C# 10,您应该默认获得以下program.cs文件:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
    
app.Run();

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

注意:确保您按照推荐的方式进行配置和设置。如果您仍然需要更多详细信息,可以参考此官方文档。

英文:

> I tried removing the Program.cs file which did not fix it. I also
> tried creating a project from the "ASP.NET Core Web App" template
> which had the same issue.

Actually, while choosing a language version newer than the default can cause hard to diagnose compile-time and runtime errors. Most importantly, the latest C# compiler determines a default language version based on your project's target framework.

On top of this, Visual Studio doesn't provide a UI to change the value, but you can change it by editing the csproj file.

What causing the issue:

The issue you are having with this might occured due to numerous reasons.

First and foremost, when the framework and language version doen't match this may cause the issue. Each release of .NET runtime version has its compatible language version.

Let's have a look in following table:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Note: You can refer to this official document.

Check Runtime and Language Version Within Machine:

Another important point this that, check your .NET runtime within your machine. You can do that by following commands:

dotnet --list-sdks
dotnet --list-runtimes

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Note: You can get more details here.

Check Runtime and Language Version Within Visual Studio:

Check what value do you have within your csproj file. You should get as following:

&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net7.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;

Check Framework Version In Visual Studio:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Check Language Version In Visual Studio:

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Note: I have .NET installed in my machine and Visual studio 2022 build version 17.5.2

Output:

If you create your MVC app following above steps let's say, using .NET6 and C# 10 you should get below program.cs file by default:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Home/Error&quot;);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: &quot;default&quot;,
    pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);

app.Run();

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Why does a new project created using Visual Studio 2022 and the ASP.NET Core web app (Model, View, Controller) template not build?

Note: Make sure, you have above configuration and setup according to the recommended way. If you still need further details you can refer to this official document.

答案3

得分: 1

错误 CS5001主要与语言版本不匹配有关。C# 10.0语言版本可在.Net 6.0基础项目中使用。您可以在项目的属性=>生成=>高级中检查。

您可以在.csproj(项目/ Web项目)文件中明确添加 <LangVersion>latest</LangVersion><LangVersion>10.0</LangVersion>

您可以参考此文档https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version以获取更多信息。

英文:

Error CS5001 is mostly related to language version mismatch. C# 10.0 language version is available with .Net 6.0 base project. You can check that in Properties project => Build => Advanced

You can explicitly add &lt;LangVersion&gt;latest&lt;/LangVersion&gt; or &lt;LangVersion&gt;10.0&lt;/LangVersion&gt; in .csproj (project/web project) file

You can refer this doc https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version for more information.

答案4

得分: 0

我能确定错误的原因是文件路径中存在非法字符。

我的项目位于一个从TFS git仓库签出的父文件夹中。TFS项目的名称中包含空格,而在签出时这些空格被转换为%20。在将文件夹重命名后,我能够成功构建和运行项目。

原文件路径:My%20Git%20Repo/Projectname/
新文件路径:MyGitRepo/Projectname/

英文:

I was able to determine that the cause of the error was illegal characters in the file path.

My project was in a parent folder that had been checked out from a TFS git repository. The TFS project had spaces in the name which on checkout were converted to %20. I was able to build and run the project after renaming the folder.

Original file path: My%20Git%20Repo/Projectname/
New file path: MyGitRepo/Projectname/

huangapple
  • 本文由 发表于 2023年6月1日 23:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定