【发布时间】:2021-11-26 21:16:14
【问题描述】:
我正在处理一个 Web API 项目,当我运行它并尝试将路由用于控制器时,它不起作用,而是引发 404 错误。为什么 Web API 会忽略路由属性?
我将在下面留下代码:
[ApiController]
[Route("api/[controller]")]
public class Controller3 : ControllerBase
{
private readonly IServiceContract3 _interest;
public Controller3(IServiceContract3 interest)
{
_interest = interest;
}
[HttpGet]
[Route("[action]")]
[Route("api/Interest/GetInterests")]
public IEnumerable<Interest> GetEmployees()
{
return _interest.GetInterests();
}
[HttpPost]
[Route("[action]")]
[Route("api/Interest/AddInterest")]
public IActionResult AddInterest(Interest interest)
{
_interest.AddInterest(interest);
return Ok();
}
[HttpPost]
[Route("[action]")]
[Route("api/Interest/UpdateInterest")]
public IActionResult UpdateInterest(Interest interest)
{
_interest.UpdateInterest(interest);
return Ok();
}
[HttpDelete]
[Route("[action]")]
[Route("api/Interest/DeleteInterest")]
public IActionResult DeleteInterest(int id)
{
var existingInterest = _interest.GetInterest(id);
if (existingInterest != null)
{
_interest.DeleteInterest(existingInterest.Id);
return Ok();
}
return NotFound($"Employee Not Found with ID : {existingInterest.Id}");
}
[HttpGet]
[Route("GetInterest")]
public Interest GetInterest(int id)
{
return _interest.GetInterest(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.AddControllers();
services.AddDbContextPool<DatabaseContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DB")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DatabaseContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
context.Database.Migrate();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
如何修复路由?每次我尝试在浏览器中执行此操作时,例如 https://localhost:44316/api/Interest/GetInterests,我都会收到 404 错误。为什么会这样?
【问题讨论】:
-
当你转到
http地址时会发生什么? -
IServiceContract3在哪里注册依赖注入?