Home / Gidsen / ASP.NET Core-contactformulierintegratie (minimale API's en scheermes)
INTEGRATIEGIDS · .NET & BACKEND

ASP.NET Core-contactformulierintegratie (minimale API's en scheermes)

Stuur inzendingen van contactformulieren veilig door van ASP.NET Core Minimal API's of Razor Pages naar Lugatu met behulp van IHttpClientFactory, API-sleutels aan de serverzijde en automatische idempotentiesleutels.

1. Minimaal API-eindpunt met IHttpClientFactory

ASP.NET Core Minimal API's bieden een schone, krachtige manier om inzendingen van contactformulieren te ontvangen en deze veilig door te sturen naar Lugatu met behulp van IHttpClientFactory en een Idempotency-Key.

Program.cs csharp
using System.Net.Http.Headers;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

// Register resilient Lugatu HTTP client
builder.Services.AddHttpClient("Lugatu", client =>
{
    client.BaseAddress = new Uri("https://www.lugatu.com");
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", builder.Configuration["Lugatu:ApiKey"]);
});

var app = builder.Build();

app.MapPost("/api/contact", async (ContactRequest request, IHttpClientFactory clientFactory, IConfiguration config) =>
{
    // 1. Silent rejection for automated bot traps
    if (!string.IsNullOrEmpty(request.Gotcha))
    {
        return Results.Ok(new { success = true });
    }

    var client = clientFactory.CreateClient("Lugatu");
    var formId = config["Lugatu:FormId"];

    var payload = new
    {
        fields = new Dictionary<string, string?>
        {
            ["name"] = request.Name,
            ["email"] = request.Email,
            ["message"] = request.Message,
        }
    };

    using var message = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/forms/{formId}/submissions")
    {
        Content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json")
    };

    // Ensure at-most-once delivery with Idempotency-Key
    message.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());

    var response = await client.SendAsync(message);
    if (!response.IsSuccessStatusCode)
    {
        return Results.StatusCode((int)response.StatusCode);
    }

    return Results.Ok(new { success = true });
});

app.Run();

public record ContactRequest(string Name, string Email, string Message, string? Gotcha);

2. Configuratie in appsettings.json

Bewaar uw Lugatu-inloggegevens veilig met behulp van ASP.NET Core-configuratieproviders. Gebruik in productie Azure Key Vault, AWS Secrets Manager of omgevingsvariabelen.

appsettings.json json
{
  "Lugatu": {
    "FormId": "YOUR_FORM_GUID",
    "ApiKey": "lug_live_your_secret_server_key"
  }
}

3. Implementatie van Razor Pages-controller

Voor traditionele ASP.NET Core MVC- of Razor Pages-apps met meerdere pagina's kunt u formulierinzendingen doorsturen binnen OnPostAsync terwijl u profiteert van de ingebouwde ASP.NET Core-tokenverificatie.

Pages/Contact.cshtml.cs csharp
public class ContactModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;
    private readonly string _formId;

    public ContactModel(IHttpClientFactory clientFactory, IConfiguration config)
    {
        _clientFactory = clientFactory;
        _formId = config["Lugatu:FormId"]!;
    }

    [BindProperty]
    public ContactInput Input { get; set; } = new();

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid || !string.IsNullOrEmpty(Input.Gotcha))
        {
            return Page();
        }

        var client = _clientFactory.CreateClient("Lugatu");
        var content = new StringContent(
            JsonSerializer.Serialize(new { fields = Input }),
            System.Text.Encoding.UTF8,
            "application/json");

        content.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());

        var res = await client.PostAsync($"/api/v1/forms/{_formId}/submissions", content);
        if (res.IsSuccessStatusCode)
        {
            return RedirectToPage("/ContactSuccess");
        }

        ModelState.AddModelError(string.Empty, "Unable to deliver inquiry. Please try again.");
        return Page();
    }
}

Beveiliging en authenticatie invariant

Technische invariant: Server-to-server API-sleutels (lug_live_...) moeten strikt op de backend worden bewaard. Bewaar ze in appsettings.json of geheime kluizen; verzend nooit live sleutels naar clientbrowsers.

Problemen oplossen en veel voorkomende inslikfouten

HTTP 401 Ongeautoriseerd antwoord van Lugatu API

Controleer of uw API-sleutel begint met lug_live_ en wordt doorgegeven in de header Authorization: Bearer. Zorg ervoor dat de API-sleutel tot de werkruimte behoort die de beoogde formulier-ID bevat.

Veelgestelde vragen

Waarom zou ik IHttpClientFactory gebruiken in plaats van een nieuwe HttpClient-instantie te maken?

IHttpClientFactory beheert socket-pooling en voorkomt socket-uitputting onder zware belasting in ASP.NET Core-applicaties.

Klaar om uw formuliereindpunt te maken?

Ga binnen enkele seconden gratis aan de slag. Geen creditcard vereist.

Begin gratis →