Skip to main content

Quick Start Guide

This guide will help you quickly understand and use the key utilities in MvcCore Utilidades through practical, real-world examples.

File Upload Management

The HelperPathProvider utility simplifies file path handling for uploads.

Basic File Upload Example

Here’s how to implement file uploads using the actual controller code:
Controllers/UploadFilesController.cs
using Microsoft.AspNetCore.Mvc;
using MvcNetCoreUtilidades.Helpers;

public class UploadFilesController : Controller
{
    private HelperPathProvider helper;

    public UploadFilesController(HelperPathProvider helper)
    {
        this.helper = helper;
    }

    [HttpPost]
    public async Task<IActionResult> SubirFile(IFormFile fichero)
    {
        string fileName = fichero.FileName;
        
        // Get physical path for saving
        string path = this.helper.MapPath(fileName, Folders.Images);
        
        // Get URL path for displaying
        string urlPath = this.helper.MapUrlPath(fileName, Folders.Images);
        
        // Save file using Stream
        using (Stream stream = new FileStream(path, FileMode.Create))
        {
            await fichero.CopyToAsync(stream);
        }
        
        ViewData["MENSAJE"] = "Fichero subido a " + path;
        ViewData["URLPATH"] = urlPath;
        return View();
    }
}

Using HelperPathProvider

The helper provides two key methods:
// Get server file system path
string path = helper.MapPath("image.jpg", Folders.Images);
// Returns: /var/www/app/wwwroot/images/image.jpg

Available Folder Types

Helpers/HelperPathProvider.cs
public enum Folders
{
    Images,      // wwwroot/images/
    facturas,    // wwwroot/facturas/
    Uploads,     // wwwroot/uploads/
    Temporal     // wwwroot/temp/
}
The HelperPathProvider is registered as a Singleton service, so it’s shared across all requests for optimal performance.

Cryptography & Hashing

The HelperCryptography class provides two encryption methods for different use cases.
1

Encrypt Content with Generated Salt

// First time encryption - generates new salt
string password = "mySecurePassword123";
string encrypted = HelperCryptography.CifrarContenido(password, comparar: false);

// Store both encrypted string and salt
string salt = HelperCryptography.Salt;
// Save to database: encrypted + salt
2

Compare Passwords

// For login - compare with existing salt
HelperCryptography.Salt = storedSalt; // Set stored salt first
string attempt = HelperCryptography.CifrarContenido(userInput, comparar: true);

if (attempt == storedEncrypted)
{
    // Password matches!
}

SHA1 Basic Encryption (For Non-Sensitive Data)

// Simple hash without salt
string content = "data-to-hash";
string hashed = HelperCryptography.EncriptarTextoBasico(content);

// Compare
string newHash = HelperCryptography.EncriptarTextoBasico(userInput);
if (newHash == hashed)
{
    // Match!
}

Real Controller Implementation

Controllers/CifradosController.cs
[HttpPost]
public IActionResult CifradoEficiente(string contenido, string resultado, string accion)
{
    if (accion.ToLower() == "cifrar")
    {
        // Encrypt new content
        string response = HelperCryptography.CifrarContenido(contenido, false);
        ViewData["TEXTOCIFRADO"] = response;
        ViewData["SALT"] = HelperCryptography.Salt;
    }
    else if (accion.ToLower() == "comparar")
    {
        // Compare with existing
        string response = HelperCryptography.CifrarContenido(contenido, true);
        if (response != resultado)
        {
            ViewData["MENSAJE"] = "Los datos son distintos...";
        }
        else
        {
            ViewData["MENSAJE"] = "Los datos son IGUALES!!!";
        }
    }
    return View();
}
The SHA512 implementation uses 12 iterations of hashing for added security. Store the salt separately - you’ll need it for password verification!

Memory Caching

Implement both custom and distributed caching strategies.

Custom In-Memory Cache with Expiration

Controllers/CachingController.cs
private IMemoryCache memoryCache;

public CachingController(IMemoryCache memoryCache)
{
    this.memoryCache = memoryCache;
}

public IActionResult MemoriaPersonalizada(int? tiempo)
{
    if (tiempo == null)
    {
        tiempo = 60; // Default 60 seconds
    }
    
    string fecha = DateTime.Now.ToLongDateString() + "--" + DateTime.Now.ToLongTimeString();
    
    if (this.memoryCache.Get("FECHA") == null)
    {
        // Cache miss - store new value
        MemoryCacheEntryOptions options = new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(tiempo.Value));
        
        this.memoryCache.Set("FECHA", fecha, options);
        ViewData["MENSAJE"] = "Fecha almacenada correctamente";
        ViewData["FECHA"] = fecha;
    }
    else
    {
        // Cache hit - retrieve existing value
        fecha = this.memoryCache.Get<string>("FECHA");
        ViewData["MENSAJE"] = "Fecha recuperada correctamente";
        ViewData["FECHA"] = fecha;
    }
    
    return View();
}

Distributed Response Caching

Controllers/CachingController.cs
[ResponseCache(Duration = 15, Location = ResponseCacheLocation.Client)]
public IActionResult MemoriaDistribuida()
{
    string fecha = DateTime.Now.ToLongDateString() + "--" + DateTime.Now.ToLongTimeString();
    ViewData["FECHA"] = fecha;
    return View();
}

IMemoryCache

Server-side caching - Data stored in application memory with custom expiration

ResponseCache

Client-side caching - HTTP cache headers for browser/CDN caching

Cache Configuration Options

// Cache expires after fixed time
var options = new MemoryCacheEntryOptions()
    .SetAbsoluteExpiration(TimeSpan.FromMinutes(10));

Session Management

Implement user authentication and state management with sessions.

Login Implementation

Controllers/HomeController.cs
public IActionResult LogIn()
{
    return View();
}

[HttpPost]
public IActionResult LogIn(string usuario)
{
    // Store user in session
    HttpContext.Session.SetString("USUARIO", usuario);
    ViewData["MENSAJE"] = "Usuario en el sistema";
    return View();
}

public IActionResult LogOut()
{
    // Remove user from session
    HttpContext.Session.Remove("USUARIO");
    return RedirectToAction("Index");
}

Reading Session Data

// In any controller or view
string? usuario = HttpContext.Session.GetString("USUARIO");

if (!string.IsNullOrEmpty(usuario))
{
    // User is logged in
    ViewData["CurrentUser"] = usuario;
}
else
{
    // Redirect to login
    return RedirectToAction("LogIn", "Home");
}

Session Helper Methods

// Store string
HttpContext.Session.SetString("Key", "Value");

// Retrieve string
string? value = HttpContext.Session.GetString("Key");
Session configuration is already set up in Program.cs with AddDistributedMemoryCache() and AddSession(). Sessions are stored in memory by default.

Email Sending

Send emails through SMTP with full configuration support.
Controllers/MailsController.cs
private IConfiguration configuration;

public MailsController(IConfiguration configuration)
{
    this.configuration = configuration;
}

[HttpPost]
public async Task<IActionResult> SendMail(string to, string asunto, string mensaje)
{
    // Get credentials from configuration
    string user = this.configuration.GetValue<string>("MailSettings:Credentials:User");
    string password = this.configuration.GetValue<string>("MailSettings:Credentials:Password");
    
    // Create mail message
    MailMessage mail = new MailMessage();
    mail.From = new MailAddress(user);
    mail.To.Add(to);
    mail.Subject = asunto;
    mail.Body = mensaje;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.Normal;
    
    // Get SMTP settings
    string host = this.configuration.GetValue<string>("Server:Host");
    int port = this.configuration.GetValue<int>("Server:Port");
    bool ssl = this.configuration.GetValue<bool>("Server:Ssl");
    bool defaultCredentials = this.configuration.GetValue<bool>("Server:DefaultCredentials");
    
    // Configure SMTP client
    SmtpClient client = new SmtpClient();
    client.Host = host;
    client.Port = port;
    client.EnableSsl = ssl;
    client.UseDefaultCredentials = defaultCredentials;  // MUST be set BEFORE credentials
    
    NetworkCredential credentials = new NetworkCredential(user, password);
    client.Credentials = credentials;  // Set AFTER UseDefaultCredentials
    
    // Send email
    await client.SendMailAsync(mail);
    
    ViewData["MENSAJE"] = "Mensaje enviado correctamente.";
    return View();
}
Important: Set UseDefaultCredentials = false BEFORE setting Credentials. This is a common gotcha that causes authentication failures!

HTML Email Template Example

string htmlBody = $@"
<html>
<body style='font-family: Arial, sans-serif;'>
    <h2 style='color: #333;'>Welcome to MvcCore Utilidades!</h2>
    <p>Hello {userName},</p>
    <p>Thank you for registering. Your account is now active.</p>
    <a href='https://yourapp.com/login' 
       style='background-color: #4CAF50; color: white; padding: 10px 20px; 
              text-decoration: none; border-radius: 5px;'>
        Login Now
    </a>
</body>
</html>
";

mail.Body = htmlBody;
mail.IsBodyHtml = true;

Repository Pattern

Implement data access with the repository pattern.

Repository Example

Repositories/RepositoryCoches.cs
public class RepositoryCoches
{
    private List<Coche> Cars;

    public RepositoryCoches()
    {
        this.Cars = new List<Coche>
        {
            new Coche 
            { 
                IdCoche = 1, 
                Marca = "Pontiac", 
                Modelo = "Firebird", 
                Imagen = "https://example.com/firebird.jpg"
            },
            new Coche 
            { 
                IdCoche = 2, 
                Marca = "Volkswagen", 
                Modelo = "Escarabajo", 
                Imagen = "https://example.com/beetle.jpg"
            }
        };
    }

    public List<Coche> GetCoches()
    {
        return this.Cars;
    }

    public Coche FindCoche(int idCoche)
    {
        return this.Cars.Find(x => x.IdCoche == idCoche);
    }
}

Using Repository in Controller

Controllers/CochesController.cs
private RepositoryCoches repo;

public CochesController(RepositoryCoches repo)
{
    this.repo = repo;
}

public IActionResult Details(int idcoche)
{
    Coche car = this.repo.FindCoche(idcoche);
    return View(car);
}

public IActionResult Index()
{
    List<Coche> cars = this.repo.GetCoches();
    return View(cars);
}
The repository is registered as Transient in Program.cs, meaning a new instance is created for each request.

View Components

Create reusable UI components with ViewComponents.
ViewComponents/MenuCochesViewComponent.cs
public class MenuCochesViewComponent : ViewComponent
{
    private RepositoryCoches repo;

    public MenuCochesViewComponent(RepositoryCoches repo)
    {
        this.repo = repo;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        List<Coche> cars = this.repo.GetCoches();
        return View(cars);
    }
}

Using ViewComponent in Views

@* Synchronous invocation *@
@await Component.InvokeAsync("MenuCoches")

@* With parameters *@
@await Component.InvokeAsync("MenuCoches", new { maxItems = 5 })

@* As tag helper *@
<vc:menu-coches max-items="5"></vc:menu-coches>

Partial Views for AJAX

Load dynamic content with partial views.
Controllers/CochesController.cs
public IActionResult _CochesPartial()
{
    return PartialView("_CochesPartial", this.Cars);
}

public IActionResult _CochesDetails(int idcoche)
{
    Coche car = this.Cars.Find(x => x.IdCoche == idcoche);
    return PartialView("_CochesDetailsView", car);
}

AJAX Call Example

// Fetch partial view content
fetch('/Coches/_CochesPartial')
    .then(response => response.text())
    .then(html => {
        document.getElementById('content').innerHTML = html;
    });

// With jQuery
$('#loadButton').click(function() {
    $('#content').load('/Coches/_CochesDetails?idcoche=1');
});

Common Patterns

Dependency Injection in Controllers

All controllers use constructor injection:
public class MyController : Controller
{
    private readonly IMemoryCache cache;
    private readonly HelperPathProvider pathHelper;
    private readonly IConfiguration configuration;

    public MyController(
        IMemoryCache cache,
        HelperPathProvider pathHelper,
        IConfiguration configuration)
    {
        this.cache = cache;
        this.pathHelper = pathHelper;
        this.configuration = configuration;
    }
}

ViewData for Passing Data to Views

// In controller
ViewData["Message"] = "Success!";
ViewData["User"] = currentUser;
ViewData["Items"] = itemList;

// In view
<p>@ViewData["Message"]</p>
<h2>@ViewData["User"]</h2>

Next Steps

Explore Controllers

Dive deeper into each controller’s implementation in the source code

Customize Helpers

Extend the helper classes to fit your specific needs

Add Your Features

Build on top of these utilities to create your application

Best Practices

Study the code patterns for ASP.NET Core development
All code examples are taken directly from the MvcCore Utilidades source code. You can find the complete implementations in the respective controller and helper files.

Build docs developers (and LLMs) love