Cấp bậc tác giả:

TRAINING

Sử dụng Filter trong ASP.NET MVC Core

Được viết bởi webmaster ngày 13/11/2023 lúc 05:14 PM
Trong ASP.NET MVC Core, bạn có thể sử dụng middleware để xác thực và ủy quyền trong ứng dụng của mình.
  • 0
  • 1385

Sử dụng Filter trong ASP.NET MVC Core

1. Authentication/Authorization:
Có thể sử dụng middleware để xác thực và ủy quyền trong ứng dụng.
Để cấu hình xác thực và ủy quyền, có thể thêm các middleware tương ứng vào pipeline xử lý yêu cầu.
Ví dụ:
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});
2. Login Details of Users:
Có thể sử dụng Identity để quản lý thông tin đăng nhập của người dùng.
Ví dụ:
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    // Kiểm tra thông tin đăng nhập và xác thực người dùng
    var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
    if (result.Succeeded)
    {
        // Đăng nhập thành công, thực hiện các hành động khác
        // Redirect đến trang returnUrl nếu có
        return RedirectToLocal(returnUrl);
    }
    // Xử lý lỗi đăng nhập không thành công
    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
    return View(model);
}
3. Logging:
Có thể sử dụng các thư viện logging như Serilog, NLog, hoặc log4net để ghi log.
Ví dụ:
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Hello, world!");
        return View();
    }
}
4. Handling of Errors:
Có thể sử dụng middleware ExceptionHandler để xử lý các lỗi xảy ra trong ứng dụng.
Ví dụ:
app.UseExceptionHandler("/Home/Error");
5. Data Caching:
Có thể sử dụng Response Caching Middleware để lưu trữ bộ nhớ cache của các yêu cầu HTTP.
Ví dụ:
app.UseResponseCaching();
6. Data In/Out:
Có thể sử dụng các model binding để lấy dữ liệu từ yêu cầu HTTP và trả về dữ liệu cho phản hồi HTTP.
Ví dụ:
public IActionResult Create(ProductViewModel model)
{
    // Lưu thông tin sản phẩm vào cơ sở dữ liệu
    _productRepository.Create(model);
    return RedirectToAction("Index");
}

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML