Last active
February 2, 2023 11:13
-
-
Save beachside-project/a927c70638d1a0b1a8c5047b1eb4eac5 to your computer and use it in GitHub Desktop.
C# / Function App DI sample
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 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