Created
November 29, 2020 15:50
-
-
Save asizikov/f402a2a54b6e37a4b1a997fff5e3693e to your computer and use it in GitHub Desktop.
Azure function which prints incoming request's headers headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Primitives; | |
public static async Task<IActionResult> Run(HttpRequestMessage req, ILogger log){ | |
var ip = GetIpFromRequestHeaders(req, log); | |
log.LogInformation($"IP:[{ip}]"); | |
return new OkObjectResult(ip); | |
} | |
private static string GetIpFromRequestHeaders(HttpRequestMessage request, ILogger log){ | |
foreach(var header in request.Headers){ | |
PrintHeader(header.Key, request, log); | |
} | |
if (request.Headers.TryGetValues("X-Forwarded-For", out var values)){ | |
return values.FirstOrDefault().Split(new char[] { ',' }).FirstOrDefault(); | |
} | |
return string.Empty; | |
} | |
private static void PrintHeader(string header, HttpRequestMessage request, ILogger log ){ | |
if (request.Headers.TryGetValues(header, out var values)){ | |
foreach(var val in values){ | |
log.LogInformation($"{header}={val}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment