首页 > 解决方案 > 为什么 Asp.net core Web API 2.0 返回 Http Error 500

问题描述

我已将 api 移动到与模板提供的通常不同的文件夹结构中。

结构看起来像这样

API
  Controllers
     LoginController.cs

LoginController 有一个基本的方法

[Route("api/[Login]")]
    public class LoginController : ControllerBase
    {
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

程序.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

启动.cs

public class Startup
    {
        public IConfiguration Configuration { get; set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddOptions();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());

            app.UseMvc();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

该解决方案构建良好。当我尝试使用以下网址访问页面时,它只是设置

localhost is currently unable to handle this request.
HTTP ERROR 500

.

https://localhost:44352/api/login/get
https://localhost:44352/API/Controllers/login/get

是否需要添加一些设置才能返回内容。

标签: c#asp.net-core-2.0asp.net-core-webapi

解决方案


您没有定义默认路由,这很好,但是您完全依赖于定义了属性路由的每个控制器和操作。在您的 上LoginController,您确实有一个 route 属性,但它不正确。括号用于替换某些路由值,如区域、控制器等;这并不表示您的实际控制器名称应该在那里。换句话说,您需要[Route("api/Login")][Route("api/[controller]")],后者将由LoginASP.NET Core 替换为控制器名称, 。

此外,当使用路由属性时,动作名称不再起作用。如果不定义路由,则与定义空路由相同,即[HttpGet("")]. 因此,即使修复了控制器路由,该操作的 URL 仍然是 just /api/login而不是 /api/login/get。如果您想要get,那么您需要将路线设置为:[HttpGet("get")]


推荐阅读