Table of Contents

Class Curl

Namespace
CurlDotNet
Assembly
CurlDotNet.dll

🚀 THE MAIN CURLDOTNET CLASS - Start here!

This class lets you run ANY curl command in C# by just copying and pasting it as a string. No translation needed. No learning curve. If it works in curl, it works here.

Quick Start:

// Just paste any curl command as a string:
var response = await Curl.Execute("curl https://api.github.com");
Console.WriteLine(response.Body);  // That's it! You're done!

What is curl? curl is the universal tool for making HTTP requests from the command line. Every API documentation uses it. Now you can use those exact same commands in your C# code.

Learn more:

public static class Curl
Inheritance
Curl
Inherited Members

Remarks

Why use CurlDotNet instead of HttpClient?

  1. ✂️ Copy & Paste - Use commands directly from API docs without translation
  2. 🎓 No Learning Curve - If you know curl (everyone does), you know this
  3. 🔄 Easy Migration - Move from bash scripts to C# without rewriting
  4. 📦 All Features - Supports all 300+ curl options out of the box

Thread Safety: All methods are thread-safe. You can call them from multiple threads simultaneously.

Memory Efficiency: Responses are streamed, not loaded into memory all at once. Perfect for large files.

Sponsored by IronSoftware - creators of IronPDF, IronOCR, IronXL, and IronBarcode.

Two Ways to Use CurlDotNet:

  1. Paste curl commands: Just copy/paste any curl command string - it works!
    var result = await Curl.ExecuteAsync("curl -X POST https://api.example.com/data -H 'Content-Type: application/json' -d '{\"key\":\"value\"}'");
  2. Use fluent builder: For programmatic API with IntelliSense
    var result = await CurlRequestBuilder.Post("https://api.example.com/data").WithHeader("Content-Type", "application/json").WithJson(new { key = "value" }).ExecuteAsync();

Properties

DefaultConnectTimeoutSeconds

Sets how long to wait for a connection to be established (in seconds).

This is different from the total timeout - it only applies to making the initial connection. Like adding --connect-timeout to every curl command.

Example:

// Give servers 10 seconds to accept connection
Curl.DefaultConnectTimeoutSeconds = 10;

// If server doesn't respond in 10 seconds, fails fast
await Curl.Execute("curl https://overloaded-server.example.com");

Tip: Set this lower than DefaultMaxTimeSeconds to fail fast on dead servers.

Learn more: curl --connect-timeout documentation

public static int DefaultConnectTimeoutSeconds { get; set; }

Property Value

int

Connection timeout in seconds. 0 = no timeout. Default is 0.

DefaultFollowRedirects

Controls whether curl automatically follows HTTP redirects (301, 302, etc).

When true, acts like adding -L or --location to every command. Many APIs use redirects, so you often want this enabled.

Example:

// Enable redirect following globally
Curl.DefaultFollowRedirects = true;

// Now shortened URLs work automatically
var response = await Curl.Execute("curl https://bit.ly/example");  // Follows to final destination

// Or use -L flag per command
var response = await Curl.Execute("curl -L https://bit.ly/example");

Security note: Be careful following redirects to untrusted sources.

Learn more: curl -L documentation

public static bool DefaultFollowRedirects { get; set; }

Property Value

bool

true to follow redirects, false to stop at first response. Default is false.

DefaultInsecure

⚠️ WARNING: Disables SSL certificate validation - ONLY use for development/testing!

When true, acts like adding -k or --insecure to every command. This accepts any SSL certificate, even self-signed or expired ones.

Example (DEVELOPMENT ONLY):

#if DEBUG
// Only in debug builds for local testing
Curl.DefaultInsecure = true;

// Now works with self-signed certificates
await Curl.Execute("curl https://localhost:5001");  // Works even with invalid cert
#endif

🔴 NEVER use this in production! It makes you vulnerable to man-in-the-middle attacks.

Learn more: curl -k documentation

public static bool DefaultInsecure { get; set; }

Property Value

bool

true to skip SSL validation (DANGEROUS), false to validate (safe). Default is false.

DefaultMaxTimeSeconds

Sets a global timeout for all curl operations (in seconds).

This is like adding --max-time to every curl command automatically. Set to 0 (default) for no timeout. Individual commands can still override this.

Example:

// Set 30 second timeout for all operations
Curl.DefaultMaxTimeSeconds = 30;

// Now all commands timeout after 30 seconds
await Curl.Execute("curl https://slow-api.example.com");  // Times out after 30s

// Override for specific command
await Curl.Execute("curl --max-time 60 https://very-slow-api.example.com");  // 60s timeout

Learn more: curl --max-time documentation

public static int DefaultMaxTimeSeconds { get; set; }

Property Value

int

Timeout in seconds. 0 = no timeout (wait forever). Default is 0.

Methods

Download(string, string)

⚠️ SYNCHRONOUS file download (blocks thread).

public static CurlResult Download(string url, string outputPath)

Parameters

url string
outputPath string

Returns

CurlResult

DownloadAsync(string, string)

Download a file from a URL and save it to disk.

Downloads any file and saves it to the specified path. Shows progress if the file is large.

Example:

// Download a PDF
await Curl.Download(
    "https://example.com/manual.pdf",
    @"C:\Downloads\manual.pdf"
);

// Download with original filename
await Curl.Download(
    "https://example.com/installer.exe",
    @"C:\Downloads\installer.exe"
);

Console.WriteLine("Download complete!");

With Error Handling:

try
{
    await Curl.Download(url, "output.zip");
    Console.WriteLine("✅ Download successful");
}
catch (CurlHttpException ex) when (ex.StatusCode == 404)
{
    Console.WriteLine("❌ File not found");
}
catch (Exception ex)
{
    Console.WriteLine($"❌ Download failed: {ex.Message}");
}
public static Task<CurlResult> DownloadAsync(string url, string outputPath)

Parameters

url string

The URL of the file to download.

outputPath string

Where to save the file. Can be:

  • Full path: @"C:\Downloads\file.pdf"
  • Relative path: "downloads/file.pdf"
  • Just filename: "file.pdf" (saves to current directory)

Returns

Task<CurlResult>

A CurlResult with download information.

Remarks

This is equivalent to: Curl.Execute($"curl -o {outputPath} {url}")

For large files with progress, use Execute(string, CurlSettings) with OnProgress callback.

Execute(string)

⚠️ SYNCHRONOUS - Execute curl command and WAIT for it to complete (BLOCKS thread).

This method BLOCKS your thread until the HTTP request completes. Your application will FREEZE during this time. Only use when async is not possible.

When to use SYNC (this method):

  • ⚠️ Console applications with simple flow
  • ⚠️ Legacy code that can't use async
  • ⚠️ Unit tests (sometimes)
  • ⚠️ Quick scripts or tools
  • ❌ NEVER in UI applications (will freeze)
  • ❌ NEVER in web applications (reduces throughput)

Example - When sync is OK:

// ✅ OK - Simple console app
static void Main()
{
    var result = Curl.Execute("curl https://api.example.com");
    Console.WriteLine(result.Body);
}

// ✅ OK - Unit test
[Test]
public void TestApi()
{
    var result = Curl.Execute("curl https://api.example.com");
    Assert.AreEqual(200, result.StatusCode);
}

// ❌ BAD - Will freeze UI!
private void Button_Click(object sender, EventArgs e)
{
    var result = Curl.Execute("curl https://api.example.com"); // FREEZES UI!
    textBox.Text = result.Body;
}

⚠️ WARNING: This blocks your thread. The application cannot do anything else while waiting for the HTTP response. Use ExecuteAsync instead whenever possible!

public static CurlResult Execute(string command)

Parameters

command string

The curl command to execute

Returns

CurlResult

The result (blocks until complete)

Execute(string, CurlSettings)

⚠️ SYNCHRONOUS with settings - Blocks thread with advanced options.

public static CurlResult Execute(string command, CurlSettings settings)

Parameters

command string
settings CurlSettings

Returns

CurlResult

Execute(string, CancellationToken)

⚠️ SYNCHRONOUS with cancellation - Blocks thread but can be cancelled.

Still BLOCKS your thread, but can be cancelled. Prefer ExecuteAsync with cancellation.

// Blocks thread but can timeout
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var result = Curl.Execute("curl https://api.example.com", cts.Token);
public static CurlResult Execute(string command, CancellationToken cancellationToken)

Parameters

command string
cancellationToken CancellationToken

Returns

CurlResult

ExecuteAsync(string)

🎯 THE MAIN METHOD - Executes any curl command and returns the response.

Just paste ANY curl command as a string. It works exactly like running curl from the command line, but returns the result as a nice C# object you can work with.

Simple Example:

// Copy any curl command from documentation and paste it here:
var response = await Curl.Execute("curl https://api.github.com/users/octocat");

// Work with the response:
Console.WriteLine($"Status: {response.StatusCode}");  // 200
Console.WriteLine($"Body: {response.Body}");          // JSON data
var user = response.ParseJson<GitHubUser>();        // Parse to object

Real-World Example from Stripe Docs:

// Paste the exact command from Stripe's documentation:
var response = await Curl.Execute(@"
    curl https://api.stripe.com/v1/charges \
      -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \
      -d amount=2000 \
      -d currency=usd \
      -d source=tok_mastercard \
      -d description='My First Test Charge'
");

if (response.IsSuccess)
{
    var charge = response.ParseJson<StripeCharge>();
    Console.WriteLine($"Payment successful! ID: {charge.Id}");
}

All HTTP Methods Supported:

await Curl.Execute("curl -X GET https://api.example.com/users");     // GET (default)
await Curl.Execute("curl -X POST https://api.example.com/users");    // POST
await Curl.Execute("curl -X PUT https://api.example.com/users/123"); // PUT
await Curl.Execute("curl -X DELETE https://api.example.com/users/123"); // DELETE
await Curl.Execute("curl -X PATCH https://api.example.com/users/123"); // PATCH

Common Options:

// Headers
await Curl.Execute("curl -H 'Authorization: Bearer token123' https://api.example.com");

// POST data
await Curl.Execute("curl -d '{\"name\":\"John\"}' https://api.example.com");

// Save to file
await Curl.Execute("curl -o download.pdf https://example.com/file.pdf");

// Follow redirects
await Curl.Execute("curl -L https://short.link/abc");

// Basic auth
await Curl.Execute("curl -u username:password https://api.example.com");

// Timeout
await Curl.Execute("curl --max-time 30 https://slow-api.example.com");
public static Task<CurlResult> ExecuteAsync(string command)

Parameters

command string

Any valid curl command as a string. You can literally copy and paste from:

  • 📖 API documentation (Stripe, Twilio, GitHub, etc.)
  • 💬 Stack Overflow answers
  • 📝 Blog posts and tutorials
  • 🖥️ Your terminal history
  • 🔧 Postman's "Code" export feature
  • 🌐 Browser DevTools "Copy as cURL"

The "curl" prefix is optional - both work:

await Curl.Execute("curl https://api.example.com");  // With "curl"
await Curl.Execute("https://api.example.com");       // Without "curl"

Returns

Task<CurlResult>

A CurlResult object containing everything from the HTTP response:

  • StatusCode - HTTP status (200, 404, 500, etc.)
  • Body - Response body as string
  • Headers - All response headers as dictionary
  • IsSuccess - True if status is 200-299
  • ParseJson<T>() - Parse JSON response to your class
  • SaveToFile() - Save response to disk

See CurlResult for all available properties and methods.

Exceptions

ArgumentNullException

Thrown when command is null or empty.

// ❌ These will throw:
await Curl.Execute(null);
await Curl.Execute("");
await Curl.Execute("   ");
See Also
CurlDotNet.Curl.ExecuteAsync(System.String[])

ExecuteAsync(string, CurlSettings)

Execute with advanced settings - for when you need more control.

Use this overload when you need features beyond what curl command strings provide, like progress callbacks, custom HTTP handlers, or retry policies.

Example with Progress Reporting:

var settings = new CurlSettings
{
    OnProgress = (bytes, total) =>
    {
        var percent = (bytes * 100.0) / total;
        Console.WriteLine($"Downloaded: {percent:F1}%");
    }
};

await Curl.Execute("curl -O https://example.com/large-file.zip", settings);

Example with Custom Retry Policy:

var settings = new CurlSettings
{
    RetryCount = 3,
    RetryDelay = TimeSpan.FromSeconds(2),
    RetryOn = new[] { 500, 502, 503, 504 }  // Retry on server errors
};

await Curl.Execute("curl https://unstable-api.example.com", settings);
public static Task<CurlResult> ExecuteAsync(string command, CurlSettings settings)

Parameters

command string

Any curl command string.

settings CurlSettings

Advanced settings including:

  • OnProgress - Callback for download/upload progress
  • RetryCount - Number of retry attempts
  • RetryDelay - Delay between retries
  • CustomHttpMessageHandler - Use your own HttpMessageHandler
  • Middleware - Add custom processing pipeline

See CurlSettings for all options.

Returns

Task<CurlResult>

A CurlResult with the response.

ExecuteAsync(string, CancellationToken)

Execute a curl command with cancellation support - perfect for long-running operations.

This lets you cancel the HTTP request if it's taking too long or if the user cancels. Essential for good user experience in desktop and mobile apps.

Basic Example:

// Create a cancellation token that times out after 30 seconds
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

try
{
    var response = await Curl.Execute(
        "curl https://slow-api.example.com/large-file",
        cts.Token
    );
    Console.WriteLine("Download complete!");
}
catch (OperationCanceledException)
{
    Console.WriteLine("Download cancelled or timed out after 30 seconds");
}

User-Cancellable Download:

private CancellationTokenSource _downloadCts;

// Start download
async Task StartDownload()
{
    _downloadCts = new CancellationTokenSource();

    try
    {
        var result = await Curl.Execute(
            "curl -o large-file.zip https://example.com/huge-file.zip",
            _downloadCts.Token
        );
        MessageBox.Show("Download complete!");
    }
    catch (OperationCanceledException)
    {
        MessageBox.Show("Download cancelled by user");
    }
}

// Cancel button click
void CancelButton_Click()
{
    _downloadCts?.Cancel();  // This stops the download
}

Web API with Request Timeout:

[HttpGet]
public async Task<IActionResult> ProxyRequest(CancellationToken cancellationToken)
{
    // ASP.NET Core passes cancellation token that triggers when:
    // - Client disconnects
    // - Request timeout is reached
    // - Server is shutting down

    var result = await Curl.Execute(
        "curl https://external-api.example.com/data",
        cancellationToken  // Pass it through!
    );

    return Ok(result.Body);
}
public static Task<CurlResult> ExecuteAsync(string command, CancellationToken cancellationToken)

Parameters

command string

Any curl command string. See Execute(string) for full documentation.

cancellationToken CancellationToken

Token to cancel the operation. Get this from:

  • ⏱️ new CancellationTokenSource(TimeSpan.FromSeconds(30)) - Timeout
  • 🔘 CancellationTokenSource linked to Cancel button - User cancellation
  • 🌐 ASP.NET Core action parameter - Web request cancellation
  • 🔗 CancellationTokenSource.CreateLinkedTokenSource() - Multiple conditions

Learn more: Cancellation in .NET

Returns

Task<CurlResult>

Same as Execute(string) - a CurlResult with the response.

Remarks

Best Practices:

  1. Always dispose CancellationTokenSource when done: using var cts = new...
  2. Check token.IsCancellationRequested before starting expensive operations
  3. Pass tokens through your entire async call chain
  4. Combine multiple tokens with CreateLinkedTokenSource for complex scenarios

Exceptions

OperationCanceledException

Thrown when the operation is cancelled via the token.

try
{
    await Curl.Execute("curl https://api.example.com", cancelToken);
}
catch (OperationCanceledException)
{
    // Handle cancellation gracefully
    Console.WriteLine("Request was cancelled");
}

ExecuteManyAsync(params string[])

Execute multiple curl commands in parallel - great for performance!

Runs multiple HTTP requests at the same time, which is much faster than running them one by one. Perfect for fetching data from multiple APIs or endpoints simultaneously.

Example - Fetch Multiple APIs:

// These all run at the same time (parallel), not one after another
var results = await Curl.ExecuteMany(
    "curl https://api.github.com/users/microsoft",
    "curl https://api.github.com/users/dotnet",
    "curl https://api.github.com/users/azure"
);

// Process results - array order matches command order
Console.WriteLine($"Microsoft: {results[0].Body}");
Console.WriteLine($"DotNet: {results[1].Body}");
Console.WriteLine($"Azure: {results[2].Body}");

Example - Aggregate Data:

// Fetch from multiple services simultaneously
var results = await Curl.ExecuteMany(
    "curl https://api.weather.com/temperature",
    "curl https://api.weather.com/humidity",
    "curl https://api.weather.com/forecast"
);

// Check if all succeeded
if (results.All(r => r.IsSuccess))
{
    var temp = results[0].ParseJson<Temperature>();
    var humidity = results[1].ParseJson<Humidity>();
    var forecast = results[2].ParseJson<Forecast>();

    DisplayWeatherDashboard(temp, humidity, forecast);
}

Error Handling - Some May Fail:

var results = await Curl.ExecuteMany(commands);

for (int i = 0; i < results.Length; i++)
{
    if (results[i].IsSuccess)
    {
        Console.WriteLine($"✅ Command {i} succeeded");
    }
    else
    {
        Console.WriteLine($"❌ Command {i} failed: {results[i].StatusCode}");
    }
}
public static Task<CurlResult[]> ExecuteManyAsync(params string[] commands)

Parameters

commands string[]

Array of curl command strings to execute. Can pass as:

  • Multiple parameters: ExecuteMany(cmd1, cmd2, cmd3)
  • Array: ExecuteMany(commandArray)
  • List: ExecuteMany(commandList.ToArray())

Returns

Task<CurlResult[]>

Array of CurlResult objects in the same order as the commands. Even if some fail, you still get results for all commands.

Remarks

Performance Note: If you have 10 commands that each take 1 second, running them in parallel takes ~1 second total instead of 10 seconds sequentially!

Limit: Be respectful of APIs - don't send hundreds of parallel requests.

Get(string)

⚠️ SYNCHRONOUS GET request (blocks thread).

var result = Curl.Get("https://api.example.com"); // Blocks!
public static CurlResult Get(string url)

Parameters

url string

Returns

CurlResult

GetAsync(string)

Quick GET request - simpler syntax for basic GET operations.

When you just need to GET a URL without any options, use this shortcut method.

Example:

// Instead of:
await Curl.Execute("curl https://api.github.com/users/octocat");

// You can use:
var response = await Curl.Get("https://api.github.com/users/octocat");

// Work with response
var user = response.ParseJson<GitHubUser>();
Console.WriteLine($"Followers: {user.Followers}");
public static Task<CurlResult> GetAsync(string url)

Parameters

url string

The URL to GET. Can be HTTP or HTTPS. Query parameters can be included.

await Curl.Get("https://api.example.com/users?page=1&limit=10");

Returns

Task<CurlResult>

A CurlResult with the response.

Remarks

This is equivalent to: Curl.Execute($"curl {url}")

For GET requests with headers or auth, use the full Execute(string) method.

Post(string, string)

⚠️ SYNCHRONOUS POST request (blocks thread).

public static CurlResult Post(string url, string data)

Parameters

url string
data string

Returns

CurlResult

PostAsync(string, string)

Quick POST request - simpler syntax for posting data.

Convenient method for simple POST requests with string data.

Example:

// Post form data
var response = await Curl.Post(
    "https://api.example.com/login",
    "username=john&password=secret123"
);

// Post JSON data
var json = "{\"name\":\"John\",\"age\":30}";
var result = await Curl.Post("https://api.example.com/users", json);
public static Task<CurlResult> PostAsync(string url, string data)

Parameters

url string

The URL to POST to.

data string

The data to send in the POST body. Can be:

  • JSON string: "{\"key\":\"value\"}"
  • Form data: "key1=value1&key2=value2"
  • XML or any other string content

Returns

Task<CurlResult>

A CurlResult with the response.

Remarks

This is equivalent to: Curl.Execute($"curl -X POST -d '{data}' {url}")

For POST with headers, use PostJson(string, object) or the full Execute(string) method.

PostJson(string, object)

⚠️ SYNCHRONOUS POST with JSON (blocks thread).

public static CurlResult PostJson(string url, object data)

Parameters

url string
data object

Returns

CurlResult

PostJsonAsync(string, object)

POST with JSON data - automatically serializes objects to JSON.

The easiest way to POST JSON data. Pass any object and it's automatically serialized to JSON with the correct Content-Type header.

Example:

// Create your data object
var newUser = new
{
    name = "John Smith",
    email = "john@example.com",
    age = 30
};

// Post it as JSON automatically
var response = await Curl.PostJson("https://api.example.com/users", newUser);

// Check if successful
if (response.IsSuccess)
{
    var created = response.ParseJson<User>();
    Console.WriteLine($"User created with ID: {created.Id}");
}

Works with any object:

// Anonymous objects
await Curl.PostJson(url, new { key = "value" });

// Your classes
await Curl.PostJson(url, myUserObject);

// Collections
await Curl.PostJson(url, new[] { item1, item2, item3 });

// Dictionaries
await Curl.PostJson(url, new Dictionary<string, object> { ["key"] = "value" });
public static Task<CurlResult> PostJsonAsync(string url, object data)

Parameters

url string

The URL to POST to.

data object

Any object to serialize as JSON. Can be:

  • Anonymous objects: new { name = "John" }
  • Your classes: new User { Name = "John" }
  • Collections: new[] { 1, 2, 3 }
  • Dictionaries: Dictionary<string, object>

Returns

Task<CurlResult>

A CurlResult with the response.

Remarks

Automatically adds: Content-Type: application/json header

Uses System.Text.Json on .NET 6+ or Newtonsoft.Json on older frameworks

ToFetch(string)

Convert curl command to JavaScript fetch() code.

Generates JavaScript code that does the same thing as your curl command. Useful for web developers who need the same request in JavaScript.

Example:

var curlCommand = "curl -X GET https://api.example.com/data -H 'Authorization: Bearer token'";

string jsCode = Curl.ToFetch(curlCommand);
Console.WriteLine(jsCode);

// Output:
// fetch('https://api.example.com/data', {
//     method: 'GET',
//     headers: {
//         'Authorization': 'Bearer token'
//     }
// })
// .then(response => response.json())
// .then(data => console.log(data));
public static string ToFetch(string command)

Parameters

command string

The curl command to convert.

Returns

string

JavaScript fetch() code that does the same thing.

ToHttpClient(string)

Convert curl command to C# HttpClient code - great for learning!

Shows you exactly how to write the same request using HttpClient. Perfect for understanding what curl is doing or migrating to pure HttpClient.

Example:

var curlCommand = @"
    curl -X POST https://api.example.com/users \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer token123' \
      -d '{""name"":""John"",""age"":30}'
";

string code = Curl.ToHttpClient(curlCommand);
Console.WriteLine(code);

// Output:
// using var client = new HttpClient();
// var request = new HttpRequestMessage(HttpMethod.Post, "https://api.example.com/users");
// request.Headers.Add("Authorization", "Bearer token123");
// request.Content = new StringContent("{\"name\":\"John\",\"age\":30}",
//     Encoding.UTF8, "application/json");
// var response = await client.SendAsync(request);
public static string ToHttpClient(string command)

Parameters

command string

The curl command to convert.

Returns

string

C# code using HttpClient that does the same thing.

Remarks

Great for:

  • Learning how HttpClient works
  • Migrating from CurlDotNet to pure HttpClient
  • Understanding what curl commands actually do
  • Code generation for your projects

ToPythonRequests(string)

Convert curl command to Python requests code.

Generates Python code using the popular 'requests' library. Great for Python developers or data scientists.

Example:

var curlCommand = "curl -u user:pass https://api.example.com/data";

string pythonCode = Curl.ToPythonRequests(curlCommand);
Console.WriteLine(pythonCode);

// Output:
// import requests
//
// response = requests.get(
//     'https://api.example.com/data',
//     auth=('user', 'pass')
// )
// print(response.json())
public static string ToPythonRequests(string command)

Parameters

command string

The curl command to convert.

Returns

string

Python code using requests library.

Validate(string)

Check if a curl command is valid without executing it.

Useful for validating user input or checking commands before running them. This only checks syntax, not whether the URL actually exists.

Example:

// Check if command is valid
var validation = Curl.Validate("curl -X POST https://api.example.com");

if (validation.IsValid)
{
    Console.WriteLine("✅ Command is valid!");
    // Safe to execute
    var result = await Curl.Execute(command);
}
else
{
    Console.WriteLine($"❌ Invalid command: {validation.ErrorMessage}");
    Console.WriteLine($"Problem at position {validation.ErrorPosition}");
}

Validate User Input:

Console.Write("Enter curl command: ");
var userCommand = Console.ReadLine();

var validation = Curl.Validate(userCommand);
if (!validation.IsValid)
{
    Console.WriteLine($"Error: {validation.ErrorMessage}");
    if (validation.Suggestions.Any())
    {
        Console.WriteLine("Did you mean:");
        foreach (var suggestion in validation.Suggestions)
        {
            Console.WriteLine($"  - {suggestion}");
        }
    }
}
public static ValidationResult Validate(string command)

Parameters

command string

The curl command string to validate.

Returns

ValidationResult

A ValidationResult containing:

  • IsValid - true if command is valid
  • ErrorMessage - Description of what's wrong (if invalid)
  • ErrorPosition - Character position of error
  • Suggestions - Possible fixes for common mistakes