1.

 

// 1. Register HttpClientFactory
public void ConfigureServices(IServiceCollection services)
{
    // Other service registrations
    ;
    services.AddHttpClient();
    ;
    
    // Register your custom services
    services.AddScoped<IMyApiService, MyApiService>();
}

// 2. Create a Service Interface
public interface IMyApiService
{
    Task<string> GetApiResponseAsync();
}

// 3. Implement the Service Using HttpClientFactory
public class MyApiService : IMyApiService
{
    readonly IHttpClientFactory m_httpClientFactory;
    
    public MyApiService(IHttpClientFactory httpClientFactory)
    {
        m_httpClientFactory = httpClientFactory;
    }
    
    public async Task<string> GetApiResponseAsync()
    {
        // Create a named client or use the default client
        HttpClient client = m_httpClientFactory.CreateClient();
        
        // Make a HTTP GET request
        HttpResponseMessage response = await client.GetAsync("https://api.example.com/api/");
        
        if (response.IsSuccessStatusCode)
        {
            var sRespBody = await response.Content.ReadAsStringAsync();
            return sRespBody;
        }
        
        // Handle error
        return "Error occurred.";
    }
}

// Use the Service in a Controller
public class MyController : Controller
{
    readonly IMyApiService m_myApiService;
    
    public MyController(IMyApiService myApiService)
    {
        m_myApiService = myApiService;
    }
    
    public async Task<IActionResult> Index()
    {
        var sApiResponse = await m_myApiService.GetApiResponseAsync();
        return View(sApiResponse);
    }
}

 

2. Using Named HttpClient Instances

private static void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient("WebApiClient", config =>
    {
        config.BaseAddress = new Uri("https://localhost:5001/api/");
        config.Timeout = TimeSpan.FromSeconds(30);
        config.DefaultRequestHeaders.Clear();
    });
    
    ;
    services.AddScoped<IHttpClientFactoryService, HttpClientFactoryService>();
}

private async Task<List<TItem>> GetItemsWithHttpClientFactory<TItem>()
{
    var httpClient = m_httpClientFactory.CreateClient("WebApiClient");
    var response = await httpClient.GetAsync("items",
        HttpCompletionOption.ResponseHeadersRead);
    using (response)
    {
        response.EnsureSuccessStatusCode();
        
        var stream = await response.Content.ReadAsStreamAsync();
        var items = await JsonSerializer.DeserializeAsync<List<TItem>>(stream, m_jsopts);
        return items;
    }
}

 

3. Using Typed HttpClient Instances

// 1. Create the custom client
public class ItemsClient
{
    public HttpClient Client { get; }
    
    public ItemsClient(HttpClient client)
    {
        this.Client = client;
        this.Client.BaseAddress = new Uri("https://localhost:5001/api/");
        this.Client.Timeout = TimeSpan.FromSeconds(30);
        this.Client.DefaultRequestHeaders.Clear();
    }
}

// 2. Register
private static void ConfigureServices(IServiceCollection services)
{
    ;
    services.AddHttpClient<ItemsClient>();
    ;
}


public class HttpClientFactoryService : IHttpClientFactoryService
{
    readonly IHttpClientFactory m_httpClientFactory;
    readonly ItemsClient m_itemsClient;
    readonly JsonSerializerOptions m_jsopts;
    
    public HttpClientFactoryService(
        IHttpClientFactory httpClientFactory,
        ItemsClient itemsClients)
    {
        m_httpClientFactory = httpClientFactory;
        m_itemsClient = itemsClients;
        
        m_options = new JsonSerializerOptions { PropertyNameCaseInsentive = true };
    }
    
    private async Task<TItems> GetItemsWithTypedClient<TItem>()
    {
        var response = await m_itemsClient.Client.GetAsync("items",
            HttpCompletionOption.ResponseHeaderRead);
        using (response)
        {
            response.EnsureSuccessStatusCode();
            
            var stream = await response.Content.ReadAsStreamAsync();
            var items = await JsonSerializer.Deserialize<List<TItem>>(stream, m_jsopts);
            return items;
        }
    }
}

 

'Web > ASP.NET Core' 카테고리의 다른 글

Static files  (0) 2021.12.06

Static files are stored within the project's web root directory.

The default directory is {content root}/wwwroot,

but is can be changed with the UseWebRoot method.

 

The parameterless UseStaticFiles method overload marks the files in web root as servable.

app.UseStaticFiles();

The following markup references wwwroot/images/image.png.

<img src="~/images/image.png" class="img" alt="test image" />

the tilde character ~/ points to the web root.

 

Serve files outside of web root

A request can access the MyStaticFiles/images/image.png file by configuring the Static File Middleware as follows:

using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;

:

builder.Services.AddDirectoryBrowser();

var app = builder.Build();

:

app.UseHttpsRedirection();

app.UseStaticFiles();

var fileProvider = new PhysicalFileProvider(
    Path.Combine(app.Environment.ContentRootPath, "MyStaticFiles"));
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = fileProvider,
    RequestPath = "/StaticFiles",
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append(
            "Cache-Control", "no-store");
    }
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = fileProvider,
    RequestPath = "/DB"
});

app.UseAuthorization();
:

The following markup references MyStaticFiles/images/image.png:

<img src="~/StaticFiles/images/image.png" class="img" alt="outside image" />

Uses FileServer Middleware

using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;

:

app.UseHttpsRedirection();

app.UseStaticFiles();

var fileProvider = new PhysicalFileProvider(
    Path.Combine(app.Environment.ContentRootPath, "MyStaticFiles"));
app.UseFileServer(new FileServerOptions
{
    FileProvider = fileProvider,
    RequestPath = "/StaticFiles",
    EnableDirectoryBrowsing = true
});

app.UseAuthorization();
:

'Web > ASP.NET Core' 카테고리의 다른 글

IHttpClientFactory  (0) 2023.10.24

+ Recent posts