Search code examples
c#asp.netminimal-apis

c# Minimal API .NET 6.0, how to get the client ip?


I use this link from microsoft https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0 to create my web api.

after that, I add the database like this:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<Context>(opt => opt.UseSqlServer(
    builder.Configuration.GetConnectionString("Default")
));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();

and my functions are like this:

app.MapGet("/SomeRoute/{data}", async (long data, Context appDb) =>
{    
    var tabladata = await appDb.Table1
        .Where(some code here)
        .ToListAsync();
    return Results.Ok(tabladata);
});

And I found that I can get the IP client with this code: add this before var app = builder.Build();

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

and this after:

app.UseForwardedHeaders();

and it's looks like this in the end:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<Context>(opt => opt.UseSqlServer(
    builder.Configuration.GetConnectionString("Default")
));
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();
app.UseForwardedHeaders();

how I gonna get the IP Client that call the web api functions?

Thanks.


Solution

  • Found the solution. here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0

    they tell you how to get the HTTPContext under "Use HttpContext from minimal APIs" title. You just have to add the parameter and it works, I don´t know why, but you get the parameter if you put it there.

    app.MapGet("/", (HttpContext context) => context.Response.WriteAsync("Hello World"));
    

    after that, in this page: https://www.codegrepper.com/code-examples/csharp/asp+net+core+web+api+get+client+ip+address they tell you how to get the client ip using the context. like this:

    var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
    

    finally I modify my code like this:

    app.MapGet("/someRoute/{data}", async (
        long data, DatabaseContext appDb, HttpContext context) =>
    {
        var remoteIp = context.Connection.RemoteIpAddress;
            string clientIp = "";
            if(remoteIp != null)
            {
                clientIp = remoteIp.ToString();
            }
    

    and it works. Hope this help other persons.