【发布时间】:2021-10-02 10:41:09
【问题描述】:
之前在 .NET Framework 中工作过,现在我开始使用 .NET Core。
我正在构建一个既是 MVC 又是 Web API 的应用程序,但我的某些路由不起作用。
这是我的控制器代码:
[Route("api/[controller]")]
[ApiController]
public class ClientController : ControllerBase
{
private readonly ApplicationDbContext db;
public ClientController(ApplicationDbContext context)
{
db = context;
}
[HttpGet]
public ActionResult Get()
{
return Ok("get works");
}
[HttpGet]
public ActionResult Test()
{
return Ok("test not working");
}
[HttpGet]
[Route("api/client/input")]
public ActionResult input(int id)
{
return Ok(string.Format("Your id: {0}", id));
}
}
这是我的 startup.cs 代码:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
services.AddMvc();
}
// 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();
}
else
{
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.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
- https://localhost:5001/api/client 有效
- https://localhost:5001/api/client/test 404 错误
- https://localhost:5001/api/client/2 404 错误
- https://localhost:5001/api/client?id=2 404 错误
我已尝试为我的个人操作添加特定路线,但没有效果。
提前致谢。
【问题讨论】:
标签: c# asp.net-core-mvc asp.net-core-webapi asp.net-core-3.1