我已将 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!");
});
}
}
解决方案构建良好。当我尝试使用以下 url 访问该页面时,它只是设置
localhost is currently unable to handle this request.
HTTP ERROR 500
.
https://localhost:44352/api/login/get
https://localhost:44352/API/Controllers/login/get
是否需要添加一些设置来返回内容。
请您参考如下方法:
您没有定义默认路由,这很好,但是您完全依赖于定义了属性路由的每个 Controller 和操作。在您的 LoginController 上,您确实有一个路由属性,但它不正确。括号用于替换某些路由值,如区域、 Controller 等;这并不表示您实际的 Controller 名称应该放在那里。换句话说,您需要 [Route("api/Login")] 或 [Route("api/[controller]")],然后后者将由 ASP.NET Core 替换为 Controller 名称 Login。
此外,当使用路由属性时, Action 名称不再起作用。如果不定义路由,则与定义空路由相同,即 [HttpGet("")]。因此,即使修复了 Controller 路由,该操作的 URL 仍然只是 /api/login,不是 /api/login/get。如果您想要 get,则需要将路由设置为:[HttpGet("get")]。
