i have created an asp.net core web api and the controller works fine in development but when have published it to an iis server i get error 405
what could be the reason even after removing WebDAV module still gives the same error
what could be the reason for this error
here's my controller code :
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly UserManager _userManager;
private readonly SignInManager _signInManager;
private readonly RoleManager _roleManager;
private readonly IEmailService _emailService;
private readonly IConfiguration _configuration;
public AuthenticationController(UserManager userManager,
RoleManager roleManager, IEmailService emailService,
SignInManager signInManager, IConfiguration configuration)
{
_userManager = userManager;
_roleManager = roleManager;
_signInManager = signInManager;
_emailService = emailService;
_configuration = configuration;
}
[H ttpPost]
public async Task Register([FromBody] RegisterUser registerUser, string role)
{
//Check User Exist
var userExist = await _userManager.FindByEmailAsync(registerUser.Email);
if (userExist != null)
{
return StatusCode(StatusCodes.Status403Forbidden,
new Response { Status = "Error", Message = "User already exists!" });
}
//Add the User in the database
IdentityUser user = new()
{
Email = registerUser.Email,
SecurityStamp = Guid.NewGuid().ToString(),
UserName = registerUser.Username,
TwoFactorEnabled=true
};
if (await _roleManager.RoleExistsAsync(role))
{
var result = await _userManager.CreateAsync(user, registerUser.Password);
if (!result.Succeeded)
{
return StatusCode(StatusCodes.Status500InternalServerError,
new Response { Status = "Error", Message = "User Failed to Create" });
}
//Add role to the user....
await _userManager.AddToRoleAsync(user, role);
//Add Token to Verify the email....
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var confirmationLink = Url.Action(nameof(ConfirmEmail), "Authentication", new { token, email = user.Email }, Request.Scheme);
var message = new Message(new string[] { user.Email! }, "Confirmation email link", confirmationLink!);
_emailService.SendEmail(message);
return StatusCode(StatusCodes.Status200OK,
new Response { Status = "Success", Message = $"User created & Email Sent to {user.Email} SuccessFully" });
}
else
{
return StatusCode(StatusCodes.Status500InternalServerError,
new Response { Status = "Error", Message = "This Role Doesnot Exist." });
}
}
[H ttpGet("ConfirmEmail")]
public async Task ConfirmEmail(string token, string email)
{
var user = await _userManager.FindByEmailAsync(email);
if (user != null)
{
var result = await _userManager.ConfirmEmailAsync(user, token);
if (result.Succeeded)
{
return StatusCode(StatusCodes.Status200OK,
new Response { Status = "Success", Message = "Email Verified Successfully" });
}
}
return StatusCode(StatusCodes.Status500InternalServerError,
new Response { Status = "Error", Message = "This User Doesnot exist!" });
}
[H ttpPost]
[Route("login")]
public async Task Login([FromBody] LoginModel loginModel)
{
var user = await _userManager.FindByNameAsync(loginModel.Username);
if (user.TwoFactorEnabled)
{
await _signInManager.SignOutAsync();
await _signInManager.PasswordSignInAsync(user, loginModel.Password, false, true);
var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email");
var message = new Message(new string[] { user.Email! }, "OTP Confrimation", token);
_emailService.SendEmail(message);
return StatusCode(StatusCodes.Status200OK,
new Response { Status = "Success", Message = $"We have sent an OTP to your Email {user.Email}" });
}
if (user!=null && await _userManager.CheckPasswordAsync(user,loginModel.Password))
{
var authClaims = new List
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var userRoles = await _userManager.GetRolesAsync(user);
foreach (var role in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, role));
}
var jwtToken = GetToken(authClaims);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(jwtToken),
expiration = jwtToken.ValidTo
});
//returning the token...
}
return Unauthorized();
}
[H ttpPost]
[Route("login-2FA")]
public async Task LoginWithOTP(string code,string username)
{
var user = await _userManager.FindByNameAsync(username);
var signIn= await _signInManager.TwoFactorSignInAsync("Email", code, false, false);
if (signIn.Succeeded)
{
if (user != null )
{
var authClaims = new List
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var userRoles = await _userManager.GetRolesAsync(user);
foreach (var role in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, role));
}
var jwtToken = GetToken(authClaims);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(jwtToken),
expiration = jwtToken.ValidTo
});
//returning the token...
}
}
return StatusCode(StatusCodes.Status404NotFound,
new Response { Status = "Success", Message = $"Invalid Code" });
}
private JwtSecurityToken GetToken(List authClaims)
{
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: DateTime.Now.AddDays(2),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
return token;
}
}
thanks
mind controllPosted Dec 19, 2024, 4:33 PM
i'm calling it using : https://site.domain.net/api/authentication
my website has ssl and it's working too
i have tested the the configuration of everything by adding to the same application default controller of weatherforecast and i call it successfully by calling https://site.domain.net/weatherforecast
Jaish MathewsPosted Dec 19, 2024, 4:01 PM
Could you share which endpoint you tried to execute? In my experience, such issues typically arise due to conflicts in HTTP method usage. For instance, attempting to call a POST method endpoint using a GET request could result in such errors.
Have you deployed the API to a remote server? Is there a domain configured for the URL being used to call this API after deployment? To troubleshoot, consider adding a default
index.htmlfile to the server and checking if it loads correctly. This approach will help you isolate whether the issue is related to the application code or the infrastructure setup.mind controllPosted Dec 19, 2024, 3:05 PM
i added a space intentionaly because the rules recognizes it as a hyperlink
Amit MohantyPosted Dec 19, 2024, 1:18 PM
You have
[HttpPost]and[HttpGet]attributes in your code. Is this a typo, or have you intentionally defined them this way? If it is a typo, replace[HttpPost]with[HttpPost]and[HttpGet]with[HttpGet].