### Basic HTTP Test Setup Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/quick-start.md Set up a mock response for a specific URL and assert the result of an HTTP GET request. ```csharp [Test] public async Task CanGetUser() { using var httpTest = new HttpTest(); // Setup mock response httpTest.RespondWith(new { id = 1, name = "John" }, 200); // Execute code under test var user = await "https://api.example.com/users/1" .GetJsonAsync(); // Assert Assert.AreEqual("John", user.Name); } ``` -------------------------------- ### Install Flurl.Http Packages Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/quick-start.md Install the core URL builder or the complete HTTP client package using the NuGet Package Manager. ```bash # Core URL builder (no HTTP) PM> Install-Package Flurl # Complete HTTP client PM> Install-Package Flurl.Http # With Newtonsoft.Json support PM> Install-Package Flurl.Http.Newtonsoft ``` -------------------------------- ### Install Flurl.Http via Package Manager Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/README.md Command to install the complete Flurl HTTP client library using the .NET Package Manager Console. ```powershell # Complete HTTP client library PM> Install-Package Flurl.Http ``` -------------------------------- ### Install Flurl.Http.Newtonsoft via Package Manager Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/README.md Command to install the Flurl.Http integration with Newtonsoft.Json for older JSON serialization needs, using the .NET Package Manager Console. ```powershell # Newtonsoft.Json integration (for older JSON serialization) PM> Install-Package Flurl.Http.Newtonsoft ``` -------------------------------- ### Basic Clientless GET and POST Requests Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Demonstrates making GET and POST requests directly on URL strings without explicit client creation. Flurl.Http automatically manages client caching based on the host. ```csharp // GET request var response = await "https://api.example.com/users".GetAsync(); var users = await response.GetJsonAsync>(); // POST request var newUser = new { name = "John", email = "john@example.com" }; var response = await "https://api.example.com/users" .PostJsonAsync(newUser); // Built-in client selection handles caching var resp1 = await "https://api.example.com/users".GetAsync(); var resp2 = await "https://api.example.com/posts".GetAsync(); // Both requests use the same cached client (same host) ``` -------------------------------- ### Example: Building and Configuring an IFlurlClient Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Demonstrates how to configure a client for a specific URL, set timeout, and add an OAuth bearer token before building it. ```csharp var client = FlurlHttp.ConfigureClientForUrl("https://api.example.com") .Configure (c => { c.Settings.Timeout = TimeSpan.FromSeconds(30); c.WithOAuthBearerToken("token"); }) .Build(); ``` -------------------------------- ### Example: Manipulating Query Parameters Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Demonstrates adding, adding or replacing, removing, and clearing query parameters on a URL. ```csharp var url = new Url("https://example.com"); url.QueryParams.Add("x", 1); url.QueryParams.Add("y", 2); url.QueryParams.AddOrReplace("x", 10); // Replaces x=1 with x=10 url.QueryParams.Remove("y"); // Removes y=2 Console.WriteLine(url.Query); // "x=10" ``` -------------------------------- ### Example LoggingHandler Implementation Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md An example implementation of IFlurlEventHandler that logs different types of Flurl events to the console. This handler demonstrates how to process BeforeCall, AfterCall, OnError, and OnRedirect events. ```csharp public class LoggingHandler : IFlurlEventHandler { public async Task OnEventAsync(FlurlEventType eventType, FlurlCall call) { switch (eventType) { case FlurlEventType.BeforeCall: Console.WriteLine($"→ {call.HttpRequestMessage.Method} {call.Request.Url}"); break; case FlurlEventType.AfterCall: Console.WriteLine($"← {call.Response?.StatusCode}"); break; case FlurlEventType.OnError: Console.WriteLine($"✗ Error: {call.Exception?.Message}"); break; case FlurlEventType.OnRedirect: Console.WriteLine($"→ Redirect to {call.Redirect?.Uri}"); break; } } } // Usage var client = new FlurlClient("https://api.example.com") .AddEventHandler(FlurlEventType.BeforeCall, new LoggingHandler()) .AddEventHandler(FlurlEventType.AfterCall, new LoggingHandler()); ``` -------------------------------- ### Install Flurl (URL Builder Only) via Package Manager Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/README.md Command to install only the Flurl URL builder component, without HTTP capabilities, using the .NET Package Manager Console. ```powershell # URL builder only (without HTTP) PM> Install-Package Flurl ``` -------------------------------- ### Perform a Simple GET Request Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/quick-start.md Execute a GET request to retrieve JSON data and deserialize it into a C# object. Can also be used to get raw string content. ```csharp // Simple GET var response = await "https://api.example.com/users/123".GetAsync(); var json = await response.GetJsonAsync(); // Or in one call var user = await "https://api.example.com/users/123".GetJsonAsync(); // As string var html = await "https://example.com/page".GetStringAsync(); ``` -------------------------------- ### Complete HttpTest Example for User Creation Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md This snippet shows a comprehensive test case for creating a user. It sets up mock responses for login and user creation, executes the application logic, and verifies that the correct HTTP calls were made with appropriate headers and content types. ```csharp using Flurl.Http.Testing; using System.Net.Http; using NUnit.Framework; [Test] public async Task CanCreateUser() { using (var httpTest = new HttpTest()) { // Setup responses httpTest.ForCallsTo("*/api/users") .RespondWith(new { id = 1, name = "John", email = "john@example.com" }, 201); httpTest.ForCallsTo("*/api/auth/login") .RespondWith(new { token = "abc123" }, 200); // Execute code under test var authClient = new AuthService(); var token = await authClient.LoginAsync("user@example.com", "password"); var userClient = new UserService(token); var newUser = await userClient.CreateUserAsync("John", "john@example.com"); // Assert Assert.AreEqual(1, newUser.Id); Assert.AreEqual("John", newUser.Name); // Verify calls httpTest.ShouldHaveCalled("*/api/auth/login") .WithVerb(HttpMethod.Post) .Times(1); httpTest.ShouldHaveCalled("*/api/users") .WithVerb(HttpMethod.Post) .WithHeader("Authorization", "Bearer abc123") .WithContentType("application/json") .Times(1); } } ``` -------------------------------- ### Example Usage of ToString() Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-call.md Demonstrates how the ToString() method of FlurlCall can be used for logging the HTTP verb and URL before a call is made. ```csharp client.OnBeforeCall(call => { Console.WriteLine($"Calling: {call}"); // e.g., "GET https://api.example.com/users" }); ``` -------------------------------- ### Send GET Request with FlurlClient Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-client.md Use this extension method to send an asynchronous GET request. It utilizes the client's BaseUrl and allows for specifying completion options and a cancellation token. ```csharp public static Task GetAsync(this IFlurlClient client, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, CancellationToken cancellationToken = default) ``` ```csharp var client = new FlurlClient("https://api.example.com/users"); var response = await client.GetAsync(); ``` -------------------------------- ### Example: Accessing and Modifying Query Parameters by Indexer Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Shows how to retrieve a query parameter's value using its name and how to update it. ```csharp var url = new Url("https://example.com?page=1&size=10"); var page = url.QueryParams["page"]; // "1" url.QueryParams["page"] = "2"; ``` -------------------------------- ### Create and Use HttpTest Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Instantiates HttpTest to activate test mode and sets up a mock response. This example demonstrates making a call that will be intercepted and return the mocked response. ```csharp using var httpTest = new HttpTest(); httpTest.RespondWith("Success", 200); var response = await "https://api.example.com/users".GetAsync(); // No actual HTTP request made; response is from the test setup ``` -------------------------------- ### Binary Data Handling Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-response.md Explains how to get binary data, such as images or files, as a byte array or stream for further processing. ```APIDOC ## Binary Data Handling ### Description Retrieve binary data as a byte array or stream. Useful for downloading files or images. ### Method `GetBytesAsync()` `GetStreamAsync()` ### Endpoint `/image.png` (example) `/large-file.bin` (example) ### Request Example ```csharp // Get image as bytes var imageBytes = await "https://example.com/image.png" .GetBytesAsync(); // Stream large file using var stream = await "https://example.com/large-file.bin" .GetStreamAsync(); using var fileStream = System.IO.File.Create("output.bin"); await stream.CopyToAsync(fileStream); ``` ### Response #### Success Response (200) - **byte[]** - For `GetBytesAsync()`. - **Stream** - For `GetStreamAsync()`. ``` -------------------------------- ### Default Client Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Gets or sets the default client used when no specific client name is requested. ```csharp public IFlurlClient Default { get; set; } ``` -------------------------------- ### Get Client by Name Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Retrieves a client from the cache by its name. Returns null if no client with the specified name is found. ```csharp public IFlurlClient Get(string name) ``` -------------------------------- ### Default Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Gets or sets the default IFlurlClient used when no specific client name is requested. ```APIDOC ## Default ### Description Gets or sets the default client used when no specific client name is requested. ### Property Type `IFlurlClient` ``` -------------------------------- ### Get and Set URL Host Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Accesses the host portion of the URL (e.g., 'www.site.com'). Does not include user info or port. ```csharp public string Host { get; set; } ``` ```csharp var url = new Url("https://user:pass@example.com:8080/path"); Console.WriteLine(url.Host); // "example.com" ``` -------------------------------- ### Get and Set URL User Info Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Accesses the user information component (e.g., 'user:pass'). Returns an empty string if not present. ```csharp public string UserInfo { get; set; } ``` ```csharp var url = new Url("https://admin:secret@example.com"); Console.WriteLine(url.UserInfo); // "admin:secret" ``` -------------------------------- ### ConfigureClientForUrl Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Gets a builder for configuring the IFlurlClient that would be selected for calling the given URL when using the clientless pattern. This is useful for configuring clients before making requests. ```APIDOC ## ConfigureClientForUrl(string url) ### Description Gets a builder for configuring the `IFlurlClient` that would be selected for calling the given URL when using the clientless pattern. This is useful for configuring clients before making requests. ### Method Signature ```csharp public static IFlurlClientBuilder ConfigureClientForUrl(string url) ``` ### Parameters #### Path Parameters - **url** (string) - Yes - The URL for which to configure the client ### Returns An `IFlurlClientBuilder` for fluent configuration. ### Example ```csharp FlurlHttp.ConfigureClientForUrl("https://api.example.com") .WithBasicAuth("user", "pass") .WithHeader("X-API-Version", "2.0"); // Now requests to https://api.example.com will use those settings var response = await "https://api.example.com/users".GetAsync(); ``` ``` -------------------------------- ### Configure Client for a Specific URL Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Gets a builder to configure the IFlurlClient for a given URL using the clientless pattern. Useful for setting up default authentication or headers before making requests. ```csharp public static IFlurlClientBuilder ConfigureClientForUrl(string url) ``` ```csharp FlurlHttp.ConfigureClientForUrl("https://api.example.com") .WithBasicAuth("user", "pass") .WithHeader("X-API-Version", "2.0"); // Now requests to https://api.example.com will use those settings var response = await "https://api.example.com/users".GetAsync(); ``` -------------------------------- ### Host Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets or sets the host portion of the URL (e.g., "www.site.com"). Does not include user info or port. ```APIDOC ## Host Property ### Description Gets or sets the host portion of the URL (e.g., "www.site.com"). Does not include user info or port. ### C# Signature ```csharp public string Host { get; set; } ``` ### Example ```csharp var url = new Url("https://user:pass@example.com:8080/path"); Console.WriteLine(url.Host); // "example.com" ``` ``` -------------------------------- ### Testing HTTP Calls with HttpTest Source: https://github.com/tmenier/flurl/blob/dev/README.md This example shows how to use HttpTest to fake and record HTTP calls within a unit test. It sets up a mock response and asserts that a specific call was made with the correct verb and content type. ```cs [Test] public void Can_Create_Person() { // fake & record all http calls in the test subject using var httpTest = new HttpTest(); // arrange httpTest.RespondWith("OK", 200); // act await sut.CreatePersonAsync("Frank", "Reynolds"); // assert httpTest.ShouldHaveCalled("http://api.mysite.com/*") .WithVerb(HttpMethod.Post) .WithContentType("application/json"); } ``` -------------------------------- ### Make a Simple Request Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/README.md Use this for quick, one-off HTTP GET requests to retrieve JSON data directly from a URL string. The library automatically handles JSON deserialization. ```csharp var user = await "https://api.example.com/users/123" .GetJsonAsync(); ``` -------------------------------- ### Settings Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Gets the FlurlHttpSettings for the test context. These settings apply globally during the test and can be used to configure serializers, timeouts, etc. ```APIDOC ## Settings ### Description Gets the `FlurlHttpSettings` for the test context. These settings apply globally during the test and can be used to configure serializers, timeouts, etc. ### Method Property Access ### Endpoint N/A ### Parameters None ### Request Example ```csharp using var httpTest = new HttpTest(); httpTest.Settings.JsonSerializer = new CustomJsonSerializer(); httpTest.RespondWith(new { result = "ok" }, 200); ``` ### Response #### Success Response Returns the `FlurlHttpSettings` object for the current test context. #### Response Example ```csharp // The settings object can be modified directly. ``` ``` -------------------------------- ### Configure API Client with Authentication and Headers Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/configuration.md Demonstrates setting up an API client with OAuth token, a specific header, and configuring default settings like timeout and redirects. ```csharp var client = new FlurlClient("https://api.github.com") .WithOAuthBearerToken(githubToken) .WithHeader("Accept", "application/vnd.github.v3+json"); client.Settings.Timeout = TimeSpan.FromSeconds(30); client.Settings.Redirects.Enabled = true; client.Settings.Redirects.MaxAutoRedirects = 5; ``` -------------------------------- ### Get and Set URL Scheme Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Accesses the URL scheme (e.g., 'http', 'https'). Does not include the ':' delimiter. Returns an empty string for relative URLs. ```csharp public string Scheme { get; set; } ``` ```csharp var url = new Url("https://example.com"); Console.WriteLine(url.Scheme); // "https" url.Scheme = "http"; // Changes to HTTP ``` -------------------------------- ### Send GET Request Async Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Use GetAsync to send an asynchronous GET request. It accepts an HttpCompletionOption to specify when the operation should complete and a CancellationToken for cancellation. ```csharp var response = await "https://api.example.com/users".GetAsync(); ``` -------------------------------- ### Configure Global, Client, and Request Settings Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/configuration.md Demonstrates how to set global HTTP configurations for a host, override them with client-specific settings, and further customize them at the request level. Use this to manage timeouts and allowed HTTP status codes. ```csharp // Global settings for all requests to this host FlurlHttp.ConfigureClientForUrl("https://api.example.com") .Settings.Timeout = TimeSpan.FromSeconds(30) .Settings.AllowedHttpStatusRange = "2xx,404"; // Client settings override global var client = new FlurlClient("https://api.example.com"); client.Settings.Timeout = TimeSpan.FromSeconds(60); // Overrides global 30s // Request settings override client var response = await client.Request("users") .WithTimeout(TimeSpan.FromSeconds(10)) // Overrides client 60s .GetAsync(); ``` -------------------------------- ### Reading Response Body as Stream Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-response.md Illustrates how to get the response body as a stream, which is efficient for handling large responses or processing data incrementally. Requires using a 'using' statement for proper disposal. ```csharp var response = await "https://api.example.com/large-file".GetAsync(); using (var stream = await response.GetStreamAsync()) { // Process the stream... } ``` -------------------------------- ### Using CookieJar for Login and Data Retrieval Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Demonstrates how to initialize a CookieJar, use it to store cookies after a login request, and then have those cookies automatically sent with subsequent requests to retrieve data. ```csharp var jar = new CookieJar(); // Login and store cookies var loginResp = await "https://api.example.com/login" .PostJsonAsync(credentials) .WithCookieJar(jar); // Cookies are automatically sent with subsequent requests var dataResp = await "https://api.example.com/data" .WithCookieJar(jar) .GetAsync(); ``` -------------------------------- ### Fragment Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets or sets the fragment component (e.g., "section1" in "https://example.com#section1"). Does not include the "#" delimiter. ```APIDOC ## Fragment Property ### Description Gets or sets the fragment component (e.g., "section1" in "https://example.com#section1"). Does not include the "#" delimiter. ### C# Signature ```csharp public string Fragment { get; set; } ``` ### Example ```csharp var url = new Url("https://example.com"); url.Fragment = "introduction"; Console.WriteLine(url.Fragment); // "introduction" ``` ``` -------------------------------- ### RespondWith(string body, int statusCode, IEnumerable> headers) Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Sets up a response with a specified string body, status code, and headers for all requests in the current test. This can be overridden by more specific configurations. ```APIDOC ## RespondWith(string body, int statusCode, IEnumerable> headers) ### Description Sets up a response with a specified string body, status code, and headers for all requests in the current test. This can be overridden by more specific configurations. ### Method POST ### Endpoint N/A (This is a method within a test framework) ### Parameters #### Request Body - **body** (string) - Required - Response body content - **statusCode** (int) - Optional - Default: 200 - HTTP status code - **headers** (IEnumerable>) - Optional - Default: null - Response headers ### Request Example ```csharp using var httpTest = new HttpTest(); httpTest.RespondWith("OK", 200); var response = await "https://api.example.com/users".GetAsync(); var body = await response.GetStringAsync(); // "OK" ``` ### Response #### Success Response (200) - **body** (string) - The content of the response body. #### Response Example ```json "OK" ``` ``` -------------------------------- ### QueryParams Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets the query parameters as a QueryParamCollection (name/value pairs). ```APIDOC ## QueryParams Property ### Description Gets the query parameters as a QueryParamCollection (name/value pairs). ### C# Signature ```csharp public QueryParamCollection QueryParams { get; } ``` ### Example ```csharp var url = new Url("https://example.com?x=1&y=2"); url.QueryParams.Add("z", "3"); ``` ``` -------------------------------- ### Scheme Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets or sets the URL scheme (e.g., "http", "https", "ftp"). Does not include the ":" delimiter. Returns empty string if the URL is relative. ```APIDOC ## Scheme Property ### Description Gets or sets the URL scheme (e.g., "http", "https", "ftp"). Does not include the ":" delimiter. Returns empty string if the URL is relative. ### C# Signature ```csharp public string Scheme { get; set; } ``` ### Example ```csharp var url = new Url("https://example.com"); Console.WriteLine(url.Scheme); // "https" url.Scheme = "http"; // Changes to HTTP ``` ``` -------------------------------- ### GetAsync Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Sends an asynchronous GET request. Allows specifying HttpCompletionOption and CancellationToken. ```APIDOC ## GET /users ### Description Sends an asynchronous GET request. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **completionOption** (HttpCompletionOption) - Optional - When to complete. Defaults to ResponseContentRead. - **cancellationToken** (CancellationToken) - Optional - Cancellation token. Defaults to default. ### Response #### Success Response (200) - **IFlurlResponse** - The response from the GET request. ### Request Example ```csharp var response = await "https://api.example.com/users".GetAsync(); ``` ``` -------------------------------- ### Create and Configure Flurl Client Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/quick-start.md Instantiate FlurlClient with a base URL and configure its settings, such as timeout, authentication tokens, and headers. This client can then be used to make multiple requests. ```csharp // Create with base URL var client = new FlurlClient("https://api.example.com"); // Configure client client.Settings.Timeout = TimeSpan.FromSeconds(30); client.WithOAuthBearerToken("token123"); client.WithHeader("User-Agent", "MyApp/1.0"); // Make requests var users = await client.Request("users").GetJsonAsync>(); var user = await client.Request("users", "123").GetJsonAsync(); ``` -------------------------------- ### Check if URL is Relative Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Determines if the URL is relative (does not start with a non-empty scheme) or absolute. ```csharp public bool IsRelative { get; } ``` ```csharp var absolute = new Url("https://example.com"); var relative = new Url("/path/to/resource"); Console.WriteLine(absolute.IsRelative); // false Console.WriteLine(relative.IsRelative); // true ``` -------------------------------- ### Enable Newtonsoft Serialization Globally (Clientless) Source: https://github.com/tmenier/flurl/blob/dev/src/Flurl.Http.Newtonsoft/README.md Use the FlurlHttp.Clients.UseNewtonsoft() shortcut to enable Newtonsoft-based serialization for the clientless pattern. ```csharp FlurlHttp.Clients.UseNewtonsoft(); ``` -------------------------------- ### ToString() Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Converts the Url object to its string representation. This is useful for getting the final URL string. ```APIDOC ## ToString() ### Description Converts the Url object to its string representation. ### Returns The complete URL as a string. ### Example ```csharp var url = new Url("https://api.example.com") .AppendPathSegment("users") .SetQueryParam("active", true); Console.WriteLine(url.ToString()); // https://api.example.com/users?active=True ``` ``` -------------------------------- ### Configure and Use Cached Flurl Client Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Demonstrates how to configure a named client in the global cache and then use it for making HTTP requests. Requires the Flurl.Http package. ```csharp FlurlHttp.Clients.Add("github", "https://api.github.com", b => { b.WithHeader("User-Agent", "MyApp"); b.WithOAuthBearerToken(githubToken); }); var repos = await "https://api.github.com/users/octocat/repos" .GetJsonAsync>(); ``` -------------------------------- ### Port Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets or sets the port number. Returns null if not explicitly specified in the URL. ```APIDOC ## Port Property ### Description Gets or sets the port number. Returns null if not explicitly specified in the URL. ### C# Signature ```csharp public int? Port { get; set; } ``` ### Example ```csharp var url = new Url("https://example.com:8443/api"); Console.WriteLine(url.Port); // 8443 ``` ``` -------------------------------- ### Get and Set URL Fragment Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Accesses the fragment component (e.g., 'section1'). Does not include the '#' delimiter. ```csharp public string Fragment { get; set; } ``` ```csharp var url = new Url("https://example.com"); url.Fragment = "introduction"; Console.WriteLine(url.Fragment); // "introduction" ``` -------------------------------- ### RespondWith(object body, int statusCode, IEnumerable> headers) Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Sets up a JSON response by serializing the provided object, along with a status code and headers. This is useful for mocking API endpoints that return JSON data. ```APIDOC ## RespondWith(object body, int statusCode, IEnumerable> headers) ### Description Sets up a JSON response by serializing the provided object, along with a status code and headers. This is useful for mocking API endpoints that return JSON data. ### Method POST ### Endpoint N/A (This is a method within a test framework) ### Parameters #### Request Body - **body** (object) - Required - Object to serialize to JSON - **statusCode** (int) - Optional - Default: 200 - HTTP status code - **headers** (IEnumerable>) - Optional - Default: null - Response headers ### Request Example ```csharp using var httpTest = new HttpTest(); httpTest.RespondWith(new { id = 1, name = "John" }, 200); var user = await "https://api.example.com/users/1".GetJsonAsync(); ``` ### Response #### Success Response (200) - **body** (object) - The serialized JSON response body. #### Response Example ```json { "id": 1, "name": "John" } ``` ``` -------------------------------- ### Configure Clientless Requests for a Host Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Shows how to configure default settings like OAuth tokens and headers for all future clientless requests to a specific host. These configurations are applied before making the actual requests. ```csharp // Configure before making requests FlurlHttp.ConfigureClientForUrl("https://api.example.com") .WithOAuthBearerToken("token") .WithHeader("User-Agent", "MyApp/1.0"); // Now all requests to that host use those settings var response = await "https://api.example.com/users".GetAsync(); ``` -------------------------------- ### Get Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Retrieves an IFlurlClient from the cache by its name. Returns null if no client with the specified name is found. ```APIDOC ## Get(string name) ### Description Gets a client by name. Returns null if not found. ### Method `Get` ### Parameters #### Path Parameters - **name** (string) - Required - The client name ### Returns - **IFlurlClient** - The cached `IFlurlClient`, or null if not found. ``` -------------------------------- ### Fluent API Chaining in C# Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/README.md Demonstrates method chaining for building and executing HTTP requests using Flurl's fluent API. This pattern simplifies complex request configurations. ```csharp var response = await url .AppendPathSegment("api") .SetQueryParam("page", 1) .WithTimeout(TimeSpan.FromSeconds(30)) .GetAsync(); ``` -------------------------------- ### Authority Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets the authority portion (user info, host, and port). Read-only computed property. ```APIDOC ## Authority Property ### Description Gets the authority portion (user info, host, and port). Read-only computed property. ### C# Signature ```csharp public string Authority { get; } ``` ### Example ```csharp var url = new Url("https://user:pass@example.com:8080"); Console.WriteLine(url.Authority); // "user:pass@example.com:8080" ``` ``` -------------------------------- ### Create a Reusable Client Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/README.md Instantiate a FlurlClient with common configurations like authentication tokens and headers for reuse across multiple requests to the same host. This promotes efficiency and consistency. ```csharp var client = new FlurlClient("https://api.example.com") .WithOAuthBearerToken("token") .WithHeader("User-Agent", "MyApp/1.0"); var users = await client.Request("users").GetJsonAsync>(); ``` -------------------------------- ### Get and Set URL Port Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Accesses the port number. Returns null if not explicitly specified in the URL. ```csharp public int? Port { get; set; } ``` ```csharp var url = new Url("https://example.com:8443/api"); Console.WriteLine(url.Port); // 8443 ``` -------------------------------- ### FlurlRequest.Headers Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Gets the collection of HTTP headers for this request. Request-level headers override client-level headers. ```APIDOC ## FlurlRequest.Headers Property ### Description Gets the collection of HTTP headers for this request. Request-level headers override client-level headers. ### Method Property Access ### Example ```csharp var request = new FlurlRequest("https://api.example.com"); request.Headers.Add("X-Custom-Header", "my-value"); ``` ``` -------------------------------- ### Url Constructor (Uri) Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Creates a new Url instance from a System.Uri object. This constructor requires a non-null Uri object. ```APIDOC ## Url(Uri uri) ### Description Creates a new Url instance from a System.Uri object. This constructor requires a non-null Uri object. ### Parameters #### Path Parameters - **uri** (Uri) - Required - A System.Uri object (required, throws ArgumentNullException if null) ### Request Example ```csharp var uri = new Uri("https://example.com:8080/api/v1"); var url = new Url(uri); ``` ``` -------------------------------- ### PatchJsonAsync Example Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Sends a PATCH request with a JSON-serialized body. Use this to update specific fields of a resource. ```csharp var response = await request.PatchJsonAsync(new { status = "active" }); ``` -------------------------------- ### Configure HttpTest for Unit Testing Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/configuration.md Illustrates how to use HttpTest to mock HTTP responses and configure test-specific settings like timeout and JSON serializer. ```csharp [Test] public async Task MyTest() { using var httpTest = new HttpTest(); // Configure test-specific settings httpTest.Settings.Timeout = TimeSpan.FromSeconds(1); httpTest.Settings.JsonSerializer = new TestJsonSerializer(); // Setup responses httpTest.RespondWith(new { result = "ok" }, 200); // Run test var response = await "https://api.example.com/endpoint".GetJsonAsync(); } ``` -------------------------------- ### Create FlurlRequest with IFlurlClient Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Demonstrates how to create a FlurlRequest and associate it with an IFlurlClient. The client provides settings and headers for the request. ```csharp var client = new FlurlClient("https://api.example.com"); var request = new FlurlRequest { Client = client }; ``` -------------------------------- ### IsRelative Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Returns true if the URL does not start with a non-empty scheme. Returns false for absolute URLs. ```APIDOC ## IsRelative Property ### Description Returns true if the URL does not start with a non-empty scheme. Returns false for absolute URLs. ### C# Signature ```csharp public bool IsRelative { get; } ``` ### Example ```csharp var absolute = new Url("https://example.com"); var relative = new Url("/path/to/resource"); Console.WriteLine(absolute.IsRelative); // false Console.WriteLine(relative.IsRelative); // true ``` ``` -------------------------------- ### Get and Set URL Query String Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Accesses the query string (e.g., 'x=1&y=2'). Does not include the '?' delimiter. ```csharp public string Query { get; set; } ``` ```csharp var url = new Url("https://example.com"); url.Query = "page=1&size=10"; Console.WriteLine(url.Query); // "page=1&size=10" ``` -------------------------------- ### Making a POST Request with JSON Data Source: https://github.com/tmenier/flurl/blob/dev/README.md This snippet demonstrates how to construct a URL, set query parameters, add an OAuth token, and send a JSON payload in a POST request. It then receives the JSON response deserialized into a specified type. ```cs var result = await "https://api.mysite.com" .AppendPathSegment("person") .SetQueryParams(new { api_key = "xyz" }) .WithOAuthBearerToken("my_oauth_token") .PostJsonAsync(new { first_name = firstName, last_name = lastName }) .ReceiveJson(); ``` -------------------------------- ### Global Flurl.Http Configuration Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Configure clients for different hosts with specific settings like OAuth tokens and headers. Also demonstrates setting a custom client caching strategy and adding global error handlers. ```csharp public class AppStartup { public static void ConfigureFlurlHttp() { // Configure clients for different hosts FlurlHttp.ConfigureClientForUrl("https://api.example.com") .WithOAuthBearerToken("api_key_123") .WithHeader("X-API-Version", "v2") .Settings.Timeout = TimeSpan.FromSeconds(30); FlurlHttp.ConfigureClientForUrl("https://cdn.example.com") .WithHeader("X-Cdn-Key", "cdn_key") .Settings.Timeout = TimeSpan.FromSeconds(60); // Or use a custom strategy FlurlHttp.UseClientCachingStrategy(req => { // Return different cache key based on host var host = req.Url?.Host ?? ""; return host.StartsWith("api") ? "api" : "default"; }); // Add global event handlers FlurlHttp.Clients.Default.OnError(call => { Console.WriteLine($"Request failed: {call}"); }); } } // In application startup: // AppStartup.ConfigureFlurlHttp(); ``` -------------------------------- ### Create Url Instance from String Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Instantiate a Url object using a string. Supports absolute, relative, or null base URLs. ```csharp var url = new Url("https://api.example.com/users"); var relativeUrl = new Url("/path/to/resource"); var emptyUrl = new Url(); ``` -------------------------------- ### GetAsync Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-client.md Sends an asynchronous GET request using the client's BaseUrl. Allows specifying HttpCompletionOption and CancellationToken. ```APIDOC ## GET / [BaseUrl] ### Description Sends an asynchronous GET request using the client's BaseUrl. ### Method GET ### Endpoint [BaseUrl] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var client = new FlurlClient("https://api.example.com/users"); var response = await client.GetAsync(); ``` ### Response #### Success Response (200) - **IFlurlResponse** (object) - The response from the GET request. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Setting and Using BaseUrl Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-client.md Configure a base URL for the IFlurlClient. Relative request URLs will be automatically combined with this base URL. ```csharp var client = new FlurlClient { BaseUrl = "https://api.example.com" }; var response = await client.Request("users", "123").GetAsync(); // Requests https://api.example.com/users/123 ``` -------------------------------- ### Current Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Gets the current HttpTest from the logical (async) call context. Returns null if no test is active. ```APIDOC ## Current ### Description Gets the current `HttpTest` from the logical (async) call context. Returns null if no test is active. ### Method Property Access ### Endpoint N/A ### Parameters None ### Request Example ```csharp var currentTest = HttpTest.Current; if (currentTest != null) { Console.WriteLine("In test mode"); } ``` ### Response #### Success Response Returns the active `HttpTest` instance or null if not in test mode. #### Response Example ```csharp // If in test mode, 'currentTest' will be an HttpTest instance. // Otherwise, 'currentTest' will be null. ``` ``` -------------------------------- ### Create Url Instance from Uri Object Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Instantiate a Url object from a System.Uri object. Ensure the Uri object is not null. ```csharp var uri = new Uri("https://example.com:8080/api/v1"); var url = new Url(uri); ``` -------------------------------- ### EndedUtc Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-call.md Gets or sets the DateTime (in UTC) when the response was received. This property is null if the call is still in progress or did not complete. ```APIDOC ## EndedUtc ### Description Gets or sets the DateTime (in UTC) when the response was received. Null if the call is still in progress or did not complete. **Type:** `DateTime?` ### Example ```csharp client.OnAfterCall(call => { if (call.EndedUtc.HasValue) { Console.WriteLine($"Response received at: {call.EndedUtc:O}"); } }); ``` ``` -------------------------------- ### Enable Newtonsoft Serialization Globally (DI/Named Clients) Source: https://github.com/tmenier/flurl/blob/dev/src/Flurl.Http.Newtonsoft/README.md Use the UseNewtonsoft() extension method on FlurlClientCache to enable Newtonsoft-based serialization when using dependency injection or named clients. ```csharp var clientCache = new FlurlClientCache().UseNewtonsoft(); ``` -------------------------------- ### PostUrlEncodedAsync Example Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Sends a POST request with a URL-encoded body. Use this for submitting form data via POST. ```csharp var response = await request.PostUrlEncodedAsync(new { key = "value" }); ``` -------------------------------- ### Configure Multiple Clients for Different URLs Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/configuration.md Shows how to configure distinct Flurl clients for different base URLs, each with its own authentication, timeout, and allowed status code settings. ```csharp // API client - stricter timeout FlurlHttp.ConfigureClientForUrl("https://api.internal.com") .WithBasicAuth("user", "pass") .Settings.Timeout = TimeSpan.FromSeconds(10); // External API - longer timeout for slow endpoints FlurlHttp.ConfigureClientForUrl("https://external-api.com") .Settings.Timeout = TimeSpan.FromSeconds(60); // File upload endpoint - allow status codes FlurlHttp.ConfigureClientForUrl("https://uploads.example.com") .Settings.AllowedHttpStatusRange = "2xx,400-410"; ``` -------------------------------- ### Add Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Adds a new IFlurlClient to the cache with a specified name, base URL, and configuration. ```APIDOC ## Add(string name, string baseUrl, Action configBuilder) ### Description Adds a new client to the cache with a base URL and configuration. ### Method `Add` ### Parameters #### Path Parameters - **name** (string) - Required - The cache key/client name - **baseUrl** (string) - Required - The base URL for the client - **configBuilder** (Action) - Required - Configuration action for the client ### Request Example ```csharp FlurlHttp.Clients.Add("github", "https://api.github.com", b => { b.WithOAuthBearerToken("token"); b.WithHeader("Accept", "application/vnd.github.v3+json"); }); var client = FlurlHttp.Clients.Get("github"); ``` ``` -------------------------------- ### RespondWith(HttpStatusCode statusCode, IEnumerable> headers) Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Sets up a response with only a specified HTTP status code and optional headers. This is useful for testing error conditions or endpoints that do not return a body. ```APIDOC ## RespondWith(HttpStatusCode statusCode, IEnumerable> headers) ### Description Sets up a response with only a specified HTTP status code and optional headers. This is useful for testing error conditions or endpoints that do not return a body. ### Method POST ### Endpoint N/A (This is a method within a test framework) ### Parameters #### Request Body - **statusCode** (HttpStatusCode) - Required - HTTP status code enum - **headers** (IEnumerable>) - Optional - Response headers ### Request Example ```csharp httpTest.RespondWith(HttpStatusCode.NotFound); ``` ### Response #### Success Response (404) - **status** (HttpStatusCode) - The HTTP status code. #### Response Example ```json 404 ``` ``` -------------------------------- ### FlurlRequest.Settings Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-request.md Gets the FlurlHttpSettings instance for this request. Request-level settings override client-level settings, which override global defaults. ```APIDOC ## FlurlRequest.Settings Property ### Description Gets the `FlurlHttpSettings` instance for this request. Request-level settings override client-level settings, which override global defaults. ### Method Property Access ### Example ```csharp var request = new FlurlRequest("https://api.example.com"); request.Settings.Timeout = TimeSpan.FromSeconds(30); request.Settings.AllowedHttpStatusRange = "3xx,418"; ``` ``` -------------------------------- ### Create FlurlClient with optional base URL Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-client.md Instantiate FlurlClient with a base URL for all subsequent requests. An internal HttpClient is automatically managed. ```csharp var client1 = new FlurlClient(); var client2 = new FlurlClient("https://api.example.com"); ``` -------------------------------- ### Get Client for a Specific Request Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-http.md Retrieves or creates the IFlurlClient that will be used for a given IFlurlRequest, applying the current caching strategy. ```csharp public static IFlurlClient GetClientForRequest(IFlurlRequest request) ``` ```csharp var request = "https://api.example.com/users".GetRequest(); var client = FlurlHttp.GetClientForRequest(request); var response = await client.SendAsync(request); ``` -------------------------------- ### Completed Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/flurl-call.md Gets a value indicating whether a response was received, irrespective of whether it signifies an error. This is true if the HttpResponseMessage is not null. ```APIDOC ## Completed ### Description Gets a value indicating whether a response was received (regardless of whether it's an error status). Returns true if `HttpResponseMessage` is not null. **Type:** `bool` ### Example ```csharp client.OnAfterCall(call => { if (call.Completed) { Console.WriteLine($"Got response: {call.Response.StatusCode}"); } else { Console.WriteLine("No response received"); } }); ``` ``` -------------------------------- ### Respond with String Body and Status Code Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/http-test.md Sets up a response with a specified string body and HTTP status code. Useful for simple text-based responses. ```csharp public HttpTestSetup RespondWith(string body, int statusCode = 200, IEnumerable> headers = null) ``` ```csharp using var httpTest = new HttpTest(); httpTest.RespondWith("OK", 200); var response = await "https://api.example.com/users".GetAsync(); var body = await response.GetStringAsync(); // "OK" ``` -------------------------------- ### Configure Global and Client Timeouts Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/configuration.md Demonstrates setting a global default timeout for a specific URL and then overriding it with a client-level timeout. Request-level timeouts can further override these. ```csharp FlurlHttp.ConfigureClientForUrl("https://api.example.com") .Settings.Timeout = TimeSpan.FromSeconds(30); var client = new FlurlClient("https://api.example.com") { Settings.Timeout = TimeSpan.FromSeconds(60) }; await client.Request("users") .Settings.Timeout = TimeSpan.FromSeconds(10) .GetAsync(); ``` -------------------------------- ### Custom JSON Serializer Implementation Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md An example implementation of the ISerializer interface using System.Text.Json. This custom serializer can be configured with JsonSerializerOptions. ```csharp public class CustomJsonSerializer : ISerializer { private readonly JsonSerializerOptions _options; public CustomJsonSerializer(JsonSerializerOptions options = null) { _options = options ?? new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; } public string Serialize(object obj) { return JsonSerializer.Serialize(obj, _options); } public T Deserialize(string s) { return JsonSerializer.Deserialize(s, _options); } } // Usage var client = new FlurlClient("https://api.example.com"); client.Settings.JsonSerializer = new CustomJsonSerializer(); ``` -------------------------------- ### Valid Flurl Configuration Settings Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/errors.md Demonstrates valid settings for Flurl's HttpVersion and Timeout to prevent FlurlConfigurationException. Ensure these values conform to expected formats and ranges. ```csharp // Use valid HTTP versions client.Settings.HttpVersion = "1.1"; // Valid client.Settings.HttpVersion = "2.0"; // Valid // Use valid timeout values client.Settings.Timeout = TimeSpan.FromSeconds(30); // Valid client.Settings.Timeout = TimeSpan.FromMilliseconds(0); // Invalid (too short) ``` -------------------------------- ### Query Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets or sets the query string (e.g., "x=1&y=2"). Does not include the "?" delimiter. ```APIDOC ## Query Property ### Description Gets or sets the query string (e.g., "x=1&y=2"). Does not include the "?" delimiter. ### C# Signature ```csharp public string Query { get; set; } ``` ### Example ```csharp var url = new Url("https://example.com"); url.Query = "page=1&size=10"; Console.WriteLine(url.Query); // "page=1&size=10" ``` ``` -------------------------------- ### Registering Global Error Handlers with FlurlClient Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/exceptions.md Illustrates how to set up a global error handler on a FlurlClient instance to manage exceptions across multiple requests without individual try-catch blocks. ```csharp var client = new FlurlClient("https://api.example.com") .OnError(call => { if (call.Exception is FlurlHttpTimeoutException) { Console.WriteLine("Timeout occurred"); } else if (call.Exception is FlurlParsingException) { Console.WriteLine("Parsing failed"); } else if (call.Response?.StatusCode == 401) { // Refresh token logic } }); ``` -------------------------------- ### Root Property Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Gets the root portion of the URL (scheme, authority) without path, query, or fragment. Read-only computed property. ```APIDOC ## Root Property ### Description Gets the root portion of the URL (scheme, authority) without path, query, or fragment. Read-only computed property. ### C# Signature ```csharp public string Root { get; } ``` ### Example ```csharp var url = new Url("https://example.com:8080/path?x=1#frag"); Console.WriteLine(url.Root); // "https://example.com:8080" ``` ``` -------------------------------- ### Configure Method Signature Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/types.md Signature for the Configure method on IFlurlClientBuilder. ```csharp public IFlurlClientBuilder Configure(Action configure) ``` -------------------------------- ### Get URL Authority Source: https://github.com/tmenier/flurl/blob/dev/_autodocs/api-reference/url.md Retrieves the authority portion of the URL, which includes user info, host, and port. This is a read-only computed property. ```csharp public string Authority { get; } ``` ```csharp var url = new Url("https://user:pass@example.com:8080"); Console.WriteLine(url.Authority); // "user:pass@example.com:8080" ```