{"id":24775055,"url":"https://github.com/berkayturkmen/microhttp","last_synced_at":"2026-04-29T11:02:21.390Z","repository":{"id":143507407,"uuid":"615834594","full_name":"berkayturkmen/MicroHttp","owner":"berkayturkmen","description":"MicroHttp is a lightweight and easy-to-use HTTP client library that is ideal for simple HTTP requests in an ASP.NET Core application. By following the steps in this document, you can easily configure and use MicroHttp in your ASP.NET Core application.","archived":false,"fork":false,"pushed_at":"2023-03-19T17:18:40.000Z","size":13,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-12-18T06:23:37.344Z","etag":null,"topics":["http","httpclient","json","microservice","rest","url"],"latest_commit_sha":null,"homepage":"https://github.com/berkayturkmen/MicroHttp","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/berkayturkmen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-18T20:13:22.000Z","updated_at":"2024-08-16T17:19:00.000Z","dependencies_parsed_at":null,"dependency_job_id":"29c27ca4-ff3c-4162-a1a5-20f6036be413","html_url":"https://github.com/berkayturkmen/MicroHttp","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/berkayturkmen%2FMicroHttp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/berkayturkmen%2FMicroHttp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/berkayturkmen%2FMicroHttp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/berkayturkmen%2FMicroHttp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/berkayturkmen","download_url":"https://codeload.github.com/berkayturkmen/MicroHttp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245184516,"owners_count":20574225,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["http","httpclient","json","microservice","rest","url"],"created_at":"2025-01-29T06:37:38.590Z","updated_at":"2026-04-29T11:02:21.382Z","avatar_url":"https://github.com/berkayturkmen.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MicroHttp\n\nMicroHttp is a high-performance HTTP client library optimized specifically for .NET 9 applications. It provides a clean, efficient interface for making HTTP requests with minimal overhead while leveraging the latest performance features.\n\n# Overview\n\nThis C# class named \"MicroHttp\" implements an interface called \"IMicroHttp\". The class provides methods for making HTTP requests using HttpClient, which is created by an instance of IHttpClientFactory.\n\nThe constructor of the class accepts an instance of IHttpClientFactory. This factory is used to create HttpClient instances with custom configurations, which are stored as named clients. The named client can be specified as a parameter to the HTTP request methods or within a RequestContext.\n\n# Key Features\n\n•\tOptimized for .NET 9: Takes full advantage of the latest performance enhancements\n•\tHigh Performance: Uses ValueTask for efficient asynchronous operations\n•\tModern C# Features: Leverages file-scoped namespaces and improved null handling\n•\tSystem.Text.Json Integration: Uses the high-performance native JSON serializer\n•\tMemory Efficient: Minimizes allocations and properly disposes of resources\n•\tImproved Error Handling: Better exception information and status code reporting\n•\tBatch Request Processing: Execute multiple HTTP requests in a single operation\n•\tDual API Design: Choose between simple parameters or flexible RequestContext\n•\tRequest/Response Interceptors: Modify requests and responses with custom logic\n•\tFile Upload Support: Simplified API for uploading single or multiple files\n•\tStreaming Support: Process large responses efficiently with streaming\n\n### Installation\n\nTo use MicroHttp in an ASP.NET Core application, first install the MicroHttp package using the NuGet Package Manager or the command line:\n\n```\ndotnet add package MicroHttp\n```\n\n# Configuration\n\nTo use MicroHttp in your ASP.NET Core application, you need to register it with the dependency injection container. To do this, add the following code to your Program.cs file:\n\n```csharp\nusing MicroHttp.Helper;\n\n// Basic configuration\nbuilder.Services.AddMicroHttp();\n\n// Custom client configuration\nbuilder.Services.AddHttpClient(\"microservice-a\", c =\u003e\n{\n    c.BaseAddress = new Uri(\"http://localhost/\");\n    c.DefaultRequestVersion = new Version(3, 0); // HTTP/3 support\n});\n```\nThe **AddMicroHttp** extension method adds the IMicroHttp interface to the dependency injection container, while the AddHttpClient method configures a named HTTP client with a base address of **http://localhost/**\n\n# Basic Usage\n\nMicroHttp offers two ways to make requests:\n\n# Simple Parameter Approach\n\n```csharp\nusing Microsoft.AspNetCore.Mvc;\nusing MicroHttp.Interfaces;\n\npublic class WeatherController : Controller\n{\n    private readonly IMicroHttp _http;\n\n    public WeatherController(IMicroHttp http)\n    {\n        _http = http;\n    }\n\n    public async Task\u003cIActionResult\u003e GetForecast(string city)\n    {\n        // Most basic request\n        var forecast = await _http.GetAsync\u003cWeatherForecast\u003e($\"api/weather/{city}\");\n        \n        // With client name\n        var forecast2 = await _http.GetAsync\u003cWeatherForecast\u003e($\"api/weather/{city}\", \"weather-service\");\n        \n        // With cancellation token\n        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));\n        var forecast3 = await _http.GetAsync\u003cWeatherForecast\u003e($\"api/weather/{city}\", null, cts.Token);\n        \n        return View(forecast);\n    }\n    \n    public async Task\u003cIActionResult\u003e CreateReport(ReportRequest request)\n    {\n        // POST request with data\n        var result = await _http.PostAsync\u003cReportResponse\u003e(\"api/reports\", request);\n        \n        return RedirectToAction(\"ViewReport\", new { id = result.ReportId });\n    }\n}\n```\n\n# RequestContext Approach\n\n```csharp\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Mvc;\nusing MicroHttp.Interfaces;\nusing MicroHttp.Models;\n\npublic class OrderController : Controller\n{\n    private readonly IMicroHttp _http;\n\n    public OrderController(IMicroHttp http)\n    {\n        _http = http;\n    }\n\n    public async Task\u003cIActionResult\u003e GetOrderDetails(int orderId)\n    {\n        // Advanced request with RequestContext\n        var context = new RequestContext\n        {\n            ClientName = \"orders-api\",\n            Headers = new Dictionary\u003cstring, string\u003e\n            {\n                [\"X-Correlation-ID\"] = Guid.NewGuid().ToString(),\n                [\"Authorization\"] = \"Bearer \" + GetUserToken()\n            },\n            CancellationToken = HttpContext.RequestAborted\n        };\n        \n        var order = await _http.GetAsync\u003cOrderDetails\u003e($\"api/orders/{orderId}\", context);\n        return View(order);\n    }\n    \n    private string GetUserToken() =\u003e User.Claims.FirstOrDefault(c =\u003e c.Type == \"token\")?.Value;\n}\n```\n\nIn this example, the Index action method injects an instance of IMicroHttp and uses the GetAsync method to make an HTTP GET request to the http://localhost/test URL. The response content is returned as a ContentResult.\n\n# RequestContext Builder\n\nYou can use the builder pattern to create RequestContext objects:\n\n```csharp\nvar context = RequestContext.CreateBuilder()\n    .WithClient(\"custom-client\")\n    .WithHeader(\"Authorization\", \"Bearer token123\")\n    .WithHeader(\"X-Correlation-ID\", Guid.NewGuid().ToString())\n    .WithCancellation(cts.Token)\n    .Build();\n\nvar response = await _http.GetAsync\u003cUserProfile\u003e(\"api/users/me\", context);\n```\n\n# Caching Policies\n\nControl how responses are cached:\n\n```csharp\n// Default 5-minute cache\nvar context = new RequestContext\n{\n    CachePolicy = CachePolicy.Default\n};\n\n// Custom cache duration with sliding expiration\nvar context = new RequestContext\n{\n    CachePolicy = new CachePolicy\n    {\n        Duration = TimeSpan.FromMinutes(10),\n        SlidingExpiration = true,\n        CustomCacheKeyParts = new[] { \"user-123\" }\n    }\n};\n\n// Force refresh cached data\nvar context = new RequestContext\n{\n    CachePolicy = new CachePolicy { ForceRefresh = true }\n};\n\n// Disable caching entirely\nvar context = new RequestContext\n{\n    CachePolicy = CachePolicy.NoCache\n};\n```\n\n# File Uploads\n\nUpload single or multiple files with form data:\n\n```csharp\npublic async Task\u003cIActionResult\u003e UploadDocument(IFormFile file)\n{\n    using var stream = file.OpenReadStream();\n    \n    // Create file upload request\n    var uploadRequest = new FileUploadRequest\n    {\n        File = new FileContent(file.FileName, stream)\n        {\n            ContentType = file.ContentType,\n            FieldName = \"document\"\n        },\n        FormFields = new Dictionary\u003cstring, string\u003e\n        {\n            [\"documentType\"] = \"invoice\",\n            [\"description\"] = \"Monthly invoice\"\n        }\n    };\n    \n    // Upload and get response\n    var result = await _http.PostFileAsync\u003cDocumentResponse\u003e(\"api/documents/upload\", uploadRequest);\n    \n    return RedirectToAction(\"ViewDocument\", new { id = result.DocumentId });\n}\n```\n\n# Streaming Support\n\nProcess large files or data streams efficiently:\n\n```csharp\n// Download and process a large file directly\nawait _http.GetStreamAsync(\"api/reports/large.csv\", async stream =\u003e \n{\n    using var fileStream = new FileStream(\"report.csv\", FileMode.Create);\n    await stream.CopyToAsync(fileStream);\n});\n\n// Process a JSON stream of objects\nvar allItems = await _http.GetJsonStreamAsync\u003cDataItem\u003e(\"api/data/stream\");\n```\n\n# Batch Request Processing\n\nExecute multiple requests in a single operation:\n\n```csharp\n// Create a batch of requests\nvar batch = new RequestBatch();\n\n// Add various request types to the batch\nvar userIndex = batch.Add\u003cUserProfile\u003e(\"api/users/current\");\nvar productsIndex = batch.Add\u003cList\u003cProduct\u003e\u003e(\"api/products/featured\");\nvar orderIndex = batch.AddPost\u003cOrderResult\u003e(\"api/orders\", new OrderRequest { ProductId = 123, Quantity = 1 });\n\n// Execute all requests in the batch\nvar results = await _http.ExecuteBatchAsync(batch);\n\n// Access the results by index and type\nvar user = results.Get\u003cUserProfile\u003e(userIndex);\nvar products = results.Get\u003cList\u003cProduct\u003e\u003e(productsIndex);\nvar order = results.Get\u003cOrderResult\u003e(orderIndex);\n\n// Check how many results were returned\nConsole.WriteLine($\"Batch returned {results.Count} results\");\n```\n\n# Request and Response Interceptors\n\nModify requests or responses with custom logic:\n\n```csharp\n// Create a request interceptor\npublic class AuthInterceptor : IRequestInterceptor\n{\n    public Task\u003cHttpRequestMessage\u003e ProcessRequestAsync(HttpRequestMessage request)\n    {\n        request.Headers.Add(\"Authorization\", \"Bearer \" + GetToken());\n        return Task.FromResult(request);\n    }\n    \n    private string GetToken() =\u003e \"your-auth-token\";\n}\n\n// Create a response interceptor\npublic class LoggingInterceptor : IResponseInterceptor\n{\n    public Task\u003cHttpResponseMessage\u003e ProcessResponseAsync(HttpResponseMessage response)\n    {\n        Console.WriteLine($\"Response status: {response.StatusCode}\");\n        return Task.FromResult(response);\n    }\n}\n\n// Use the interceptors\nvar context = new RequestContext\n{\n    RequestInterceptors = new List\u003cIRequestInterceptor\u003e { new AuthInterceptor() },\n    ResponseInterceptors = new List\u003cIResponseInterceptor\u003e { new LoggingInterceptor() }\n};\n\nvar response = await _http.GetAsync\u003cDataResponse\u003e(\"api/data\", context);\n```\n\n# Performance Optimizations\n\nThe .NET 9 version of MicroHttp includes several performance enhancements:\n•\tUses ValueTask instead of Task for better performance with short-running operations\n•\tLeverages System.Text.Json for faster serialization and deserialization\n•\tImplements targeted exception handling to minimize overhead\n•\tUses HttpCompletionOption.ResponseHeadersRead for streaming response handling\n•\tSpecial optimizations for string responses\n•\tEfficient HTTP header handling\n•\tProper resource disposal to prevent memory leaks\n•\tSupport for modern HTTP features like HTTP/3\n\n# Error Handling\n\nMicroHttp provides improved error handling with specific exception types:\n\n```csharp\ntry\n{\n    var result = await _http.GetAsync\u003cDataResponse\u003e(\"api/data\");\n    // Process result\n}\ncatch (HttpRequestException ex)\n{\n    // Access status code and details\n    Console.WriteLine($\"HTTP error: {ex.StatusCode} - {ex.Message}\");\n}\ncatch (JsonException ex)\n{\n    // Handle deserialization errors\n    Console.WriteLine($\"JSON error: {ex.Message}\");\n}\ncatch (OperationCanceledException ex)\n{\n    // Handle timeouts or cancellations\n    Console.WriteLine(\"Request was canceled or timed out\");\n}\n```\n\n# Conclusion\nMicroHttp is a lightweight and high-performance HTTP client library that is ideal for modern ASP.NET Core applications built on .NET 9. It provides both simple and advanced APIs for making HTTP requests, with significant performance optimizations that make it efficient for everything from basic API calls to complex integration scenarios. With features like dual API design, batch processing, request contexts, caching policies, and interceptors, it offers a flexible and powerful solution for all your HTTP communication needs.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fberkayturkmen%2Fmicrohttp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fberkayturkmen%2Fmicrohttp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fberkayturkmen%2Fmicrohttp/lists"}