Hi,
I am new to ASP.Net Core. I have an MVC core application that I am trying to implement a login page. I created a table into a database for users. I would like to give an unauthorized message if the user enters the wrong username/password and if the user tries to enter a page without login, the application should redirect to the login page.
Here is my controller:
Here is the login page:
I am new to ASP.Net Core. I have an MVC core application that I am trying to implement a login page. I created a table into a database for users. I would like to give an unauthorized message if the user enters the wrong username/password and if the user tries to enter a page without login, the application should redirect to the login page.
Here is my controller:
C#:
namespace GameMonitor.Controllers
{
public class GameBanksController : Controller
{
private readonly GameContext _context;
public GameBanksController(GameContext context)
{
_context = context;
}
[Route("")]
[Route("GameBanks")]
[Route("GameBanks/Login")]
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult UserLogin(UserLogin loginModel)
{
if (Login(loginModel.Username, loginModel.Password))
{
//Just redirect to our index after logging in.
return RedirectToAction("Index", "GameBanks");
}
return RedirectToAction("Error", "Shared"); ;
}
public bool Login(string userName, string password)
{
var user = _context.UserLogins.FirstOrDefault(u => u.Username.Equals(userName, StringComparison.Ordinal) && u.Password == password);
if (user == null) return false;
return true;
}
[Authorize]
[Route("GameBanks/Index")]
// GET: GameBanks
public async Task<ActionResult<IList<GameBanks>>> Index()
{
//Group By games
var games = await _context.GameBanks.GroupBy(g =>new {g.ProductCode,g.UnitPrice,g.ProductDescription})
.Select(gcs => new GameBanks
{
ProductCode = gcs.Key.ProductCode,
ProductDescription = gcs.Key.ProductDescription,
UnitPrice = gcs.Key.UnitPrice,
Quantity = gcs.Sum(g => g.Quantity)
}).ToListAsync();
return View(games);
}
[Authorize]
// GET: GameBanks
public async Task<IActionResult> GamesList()
{
return View(await _context.GameBanks.ToListAsync());
}
[Authorize]
// GET: GameBanks/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var gameBanks = await _context.GameBanks
.FirstOrDefaultAsync(m => m.GameBankId == id);
if (gameBanks == null)
{
return NotFound();
}
return View(gameBanks);
}
}
}
Here is the login page:
C#:
@{
ViewData["Title"] = "Login";
}
<h2>Login</h2>
<form action="@Url.Action("UserLogin", "GameBanks")" method="post">
<div class="form-group">
<label>User Name</label>
<input type="text" class="form-control" name="Username" value="" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="Password" class="form-control" value="" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="name" value="Submit" />
</div>
</form>