我有一个使用 MVC 的 ASP.NET Core 应用程序,我最近向它添加了身份验证。 在本地测试时效果很好,但是当我发布应用并将其安装到另一台服务器上后,登录方法总是返回 404 错误。
奇怪的是,只有登录方法有这个问题 - 如果我打开 Postman 并向其他 API 方法之一发出请求,它将返回 401 Unauthorized (正如预期的那样,因为我没有登录) 。 所以我知道我有正确的 URL,但它仍然返回 404。
Login 方法的写法与其他方法完全相同,我能看到的唯一区别是它的属性中有 [AllowAnonymous] 而不是 [Authorize]。
我注意到的另一个奇怪之处是,它需要相当长的时间(约 30 秒)才返回 404 错误。 对其他控制器的请求没有相同的延迟。
这些都没有任何意义 - 当同一控制器上的另一个方法正确路由时,为什么该方法会失败? 为什么会出现 404 错误? 为什么它可以在我的本地机器上运行?
登录控制器:
[Produces("application/json")]
[Route("api/[controller]")]
public class LoginController : Controller
{
private readonly ILoginService _service;
private readonly CustomTokenOptions _tokenOptions;
private readonly IMemoryCache _memoryCache;
public LoginController(ILoginService service, IMemoryCache memoryCache, IConfiguration configuration)
{
_service = service;
_tokenOptions = new CustomTokenOptions();
configuration.GetSection("TokenAuthentication").Bind(_tokenOptions);
_memoryCache = memoryCache;
}
[AllowAnonymous]
[HttpPost("[action]")]
public IActionResult GetToken()
{
//Returns a JWT token
//This method returns a 404 Not Found
}
[Authorize(Policy="AllowedGroups")]
[HttpPost("[action]")]
public IActionResult Logout()
{
//This method works
}
}
客户端代码:
var basePath = $("base").first().attr("href");
function login() {
$("#btnLogin").attr("disabled", true);
username = $("#username").val();
password = $("#password").val();
request = $.ajax({
url: basePath + "api/Login/GetToken",
async: true,
type: "POST",
headers: {
username: username,
password: password
}
});
function logout() {
request = $.ajax({
url: basePath + "api/Login/Logout",
async: true,
type: "POST",
headers: {
"Authorization": "Bearer " + self.token()
}
}).then(function () {
self.loggedIn(false);
self.token("");
});
}
我为调试目的尝试过的其他事情:
删除 GetToken() 方法的内容并将其替换为
return StatusCode(200);
这意味着 GetToken 方法中没有任何内容会导致错误。注释掉我的代码中的
UseAuthentication
和 Authorize
语句。 当身份验证关闭时,错误仍然发生。将 GetToken 方法重命名为其他名称。
由@WictorZychla 回答。构造函数中的 LoginService 失败,因此错误发生在它到达控制器操作之前。
就我而言,在我的班级程序中添加此代码并且它有效
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());