c# - 为什么 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
是否需要添加一些设置才能返回内容。
解决方案
您没有定义默认路由,这很好,但是您完全依赖于定义了属性路由的每个控制器和操作。在您的 上LoginController
,您确实有一个 route 属性,但它不正确。括号用于替换某些路由值,如区域、控制器等;这并不表示您的实际控制器名称应该在那里。换句话说,您需要[Route("api/Login")]
或[Route("api/[controller]")]
,后者将由Login
ASP.NET Core 替换为控制器名称, 。
此外,当使用路由属性时,动作名称不再起作用。如果不定义路由,则与定义空路由相同,即[HttpGet("")]
. 因此,即使修复了控制器路由,该操作的 URL 仍然是 just /api/login
,而不是 /api/login/get
。如果您想要get
,那么您需要将路线设置为:[HttpGet("get")]
。
推荐阅读
- android - 5751-5751/? E/libprocessgroup: 无法创建和 chown /acct/uid_10058: 只读文件系统
- c# - 在.net中将多个事件类型添加到同一个kafka主题
- apache-kafka - debezium - 模式注册表问题
- python-3.x - 展平 Pandas DataFrame 添加后缀
- intellij-idea - Intellij IDEA 2021.2目前无法渲染markdown表?
- php - 如何强制文件使用特定版本的 php?
- python - 是否可以使用 AWS Textract 捕获 PDF 文本的特定部分?
- azure-ad-b2c - Azure AD B2C 使用开放 ID 连接协议的条款和条件自定义策略
- javascript - 如何复制跨域 iFrame 的内容?
- kubernetes - 使用 Helm 图表安装 Prometheus 时的音量问题