Skip to content

Instantly share code, notes, and snippets.

@beachside-project
Last active February 2, 2023 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beachside-project/a927c70638d1a0b1a8c5047b1eb4eac5 to your computer and use it in GitHub Desktop.
Save beachside-project/a927c70638d1a0b1a8c5047b1eb4eac5 to your computer and use it in GitHub Desktop.
C# / Function App DI sample
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(DependencyInjectionWithHttpContextSample.Startup))]
namespace DependencyInjectionWithHttpContextSample;
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddScoped(s =>
{
var accessor = s.GetRequiredService<IHttpContextAccessor>();
// Request header から "X-MS-CLIENT-PRINCIPAL-ID" の値を取得。
var userId = accessor.HttpContext.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"];
// パス "api/customers/{customerId}/order" から値を取得する
// 今回のサンプルだと "api/customers/xyz123/order" から "xyz123" を取得する感じ。
var path = accessor.HttpContext.Request.Path;
var customerId = path.ToString().Split('/')[3];
// query string の中で "hobby" の値を取得。
var hobby = accessor.HttpContext.Request.Query["hobby"];
return new SampleOptions
{
UserId = userId,
CustomerId = customerId,
Hobby = hobby
};
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment