首页 > 解决方案 > 获得 404 的简单 .Net 5.0 Web 应用程序(使用 mvc)

问题描述

.Net 新手在这里。我正在关注一个 Web 开发训练营,过去几天我遇到了一个持续存在的问题。我已经由几个助教、其他学生和一些教练运行过它,但到目前为止我们都被难住了。

在浏览器中打开 localhost:5000 页面或使用邮递员时,我收到 404。该项目是使用dotnet new web --no-https -o ProjName命令生成的,然后进行了编辑。

这是我的 Startup 的样子:

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.EnableEndpointRouting = false);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
        }
    }

这是我的控制器的样子

using Microsoft.AspNetCore.Mvc;

namespace Portfolio.Controllers
{
    class HomeController : Controller
    {
        [HttpGet("")]
        public string Index() => "This is my index";
    }
}

请注意,我在使用默认自动生成代码但未将此控制器与属性路由模式一起使用时收到响应。如果您知道如何解决这个问题,那将是一个很大的帮助,因为我落后了。

我尝试过的事情:

我很乐意提供任何其他信息,而且我通常精通技术,可以跟进建议的内容。

谢谢

标签: c#asp.net-core-mvchttp-status-code-404asp.net-core-5.0

解决方案


在属性中指定空字符串HttpGet就像指定无。

您可以在方法中定义默认路由模式useMvc

app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" });
});

或者在属性中设置一个斜线HttpGet来设置方法的根路径:

HttpGet("/")

推荐阅读