我在ASP Core(分别为2.2和3.0)中都有一个MVC应用程序和一个API,它们分别发布在IIS 10下的2个不同服务器上。Web应用程序运行良好,但API出现意外问题:路由坏了。
这是我用来从其邮政编码(codePostal)获取城市的示例方法:
[Authorize]
[ApiController]
[Route("[controller]")]
public class CommunesController : ControllerBase
{
private readonly ICommuneService _communeService;
public CommunesController(ICommuneService communeService)
{
_communeService = communeService;
}
[AllowAnonymous]
[HttpGet("{codePostal}")]
public IActionResult GetCommunesFromCP(string codePostal)
{
IList<CommuneDto> resCommunes = _communeService.GetCommunesFromCP(codePostal);
if (resCommunes == null || resCommunes.Count == 0)
return NotFound();
else
return Ok(resCommunes);
}
}
如果我使用网址https://mydomain.fr/communes/38000调用此方法,则会收到404错误。如果我使用经典的查询字符串语法https://mydomain.fr/communes?codePostal=38000,它就可以工作!我不明白为什么会这样。同样,当我在控制器中有几种带有RESTful命名的GET方法时,会因为路由丢失而调用了错误的方法!一切都在调试中运行良好,但是自从部署API以来,我一直在努力工作了几个小时。
如果可以帮助的话,这是我来自Startup.cs的API Configure方法:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
答案 0 :(得分:0)
您需要在方法之前添加[Route("GetCommunesFromCP/{codePostal}")]
,在更改后在方法下方添加
[AllowAnonymous]
[Route("GetCommunesFromCP/{codePostal}")]
public IActionResult GetCommunesFromCP(string codePostal)
{
IList<CommuneDto> resCommunes = _communeService.GetCommunesFromCP(codePostal);
if (resCommunes == null || resCommunes.Count == 0)
return NotFound();
else
return Ok(resCommunes);
}
答案 1 :(得分:0)
我终于找到问题所在:Startup.cs中app.UseAuthentication()的位置错误。我在app.UseCors(...)之前移动了它,并且在重新发布API之后路由工作正常。我看不到app.UseAuthentication()的位置与问题之间的联系,因为在两种情况下,它都在app.UseRouting()之前:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}