我有一个ASP.NET Web API路由器,当我导航到正确的路由时似乎没有受到攻击。
这是我的Web API控制器:
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
#region Declarations
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _context;
private readonly IHostingEnvironment _hostingEnvironment;
#endregion
public AccountController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext context,
IHostingEnvironment environment
)
{
_userManager = userManager;
_roleManager = roleManager;
_context = context;
_hostingEnvironment = environment;
}
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "Account", "Controller" };
}
[HttpPost]
public async Task<IActionResult> GetToken()
{
var client = new DiscoveryClient("http://localhost:15547");
client.Policy.RequireHttps = false;
var disco = await client.GetAsync();
if (disco.IsError)
{
return BadRequest(disco.Error);
}
TokenClient tokenClient = new TokenClient(disco.TokenEndpoint, "ro.angular", "secret");
TokenResponse tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("ahmer", "Default@69", "api1 openid");
if (tokenResponse.IsError)
{
return BadRequest(tokenResponse.Error);
}
//var user = _userManager.FindByNameAsync(model.UserName);
var result = await _userManager.FindByNameAsync("ahmer");
return BadRequest("Invalid username or password.");
}
}
但是,我的GET http://localhost:15547/api/account/
路由工作正常,但是当我尝试发出POST请求http://localhost:15547/api/account/GetToken
时,它没有被点击,它向我显示了来自Postman的404消息。我在代码中做错了什么。
输出1
输出2
答案 0 :(得分:2)
ASP.NET CORE默认路由不同于ASP.NET MVC默认路由系统。
现在:
[HttpPost]
public async Task<IActionResult> GetToken()
即使操作名称为POST : http://localhost:15547/api/account
,也将匹配GetToken
。所以这就是为什么你打404。
您必须将路由模板设置为“ gettoken”以使其按需工作:
[HttpPost("gettoken")]
public async Task<IActionResult> GetToken()
这将指示ASP.NET此操作应与POST http://localhost:15547/api/account/GetToken
匹配