The ImageKit C# SDK is a comprehensive library designed to simplify the integration of ImageKit into your server-side applications. It provides powerful tools for working with the ImageKit REST API, including building and transforming URLs, generating signed URLs for secure content delivery, and handling file uploads.
For additional details, refer to the ImageKit REST API documentation.
- Installation
- Requirements
- Usage
- Client configuration
- Requests and responses
- Raw responses
- URL generation
- Authentication parameters for client-side uploads
- Webhook verification
- Error handling
- Network options
- Undocumented API functionality
- Semantic versioning
Install the package from NuGet:
dotnet add package ImagekitThis library requires .NET Standard 2.0 or later.
usingSystem;usingImagekit;usingImagekit.Models.Files;ImageKitClientclient=new(){PrivateKey="private_key_xxx",};FileUploadParamsparameters=new(){File=newSystem.IO.FileStream("/path/to/your/image.jpg",System.IO.FileMode.Open),FileName="uploaded-image.jpg",};varresponse=awaitclient.Files.Upload(parameters);Console.WriteLine(response);Configure the client using environment variables:
usingImagekit;// Configured using the IMAGEKIT_PRIVATE_KEY, IMAGEKIT_WEBHOOK_SECRET and IMAGE_KIT_BASE_URL environment variablesImageKitClientclient=new();Or manually:
usingImagekit;ImageKitClientclient=new(){PrivateKey="My Private Key",};Or using a combination of the two approaches.
See this table for the available options:
| Property | Environment variable | Required | Default value |
|---|---|---|---|
PrivateKey | IMAGEKIT_PRIVATE_KEY | true | - |
WebhookSecret | IMAGEKIT_WEBHOOK_SECRET | false | - |
BaseUrl | IMAGE_KIT_BASE_URL | true | "https://api.imagekit.io" |
To temporarily use a modified client configuration, while reusing the same connection and thread pools, call WithOptions on any client or service:
usingSystem;varresponse=awaitclient.WithOptions(options =>optionswith{BaseUrl="https://example.com",Timeout=TimeSpan.FromSeconds(42),}).Files.Upload(parameters);Console.WriteLine(response);Using a with expression makes it easy to construct the modified options.
The WithOptions method does not affect the original client or service.
To send a request to the Image Kit API, build an instance of some Params class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a C# class.
For example, client.Files.Upload should be called with an instance of FileUploadParams, and it will return an instance of Task<FileUploadResponse>.
The SDK defines methods that deserialize responses into instances of C# classes. However, these methods don't provide access to the response headers, status code, or the raw response body.
To access this data, prefix any HTTP method call on a client or service with WithRawResponse:
varresponse=awaitclient.WithRawResponse.Files.Upload(parameters);varstatusCode=response.StatusCode;varheaders=response.Headers;The raw HttpResponseMessage can also be accessed through the RawMessage property.
For non-streaming responses, you can deserialize the response into an instance of a C# class if needed:
usingSystem;usingImagekit.Models.Files;varresponse=awaitclient.WithRawResponse.Files.Upload(parameters);FileUploadResponsedeserialized=awaitresponse.Deserialize();Console.WriteLine(deserialized);The ImageKit SDK provides a powerful Helper.BuildUrl() method for generating optimized image and video URLs with transformations. Here are examples ranging from simple URLs to complex transformations with overlays and signed URLs.
Generate a simple URL without any transformations:
usingImagekit;usingImagekit.Models;ImageKitClientclient=new(){PrivateKey="private_key_xxx",};stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/path/to/image.jpg",});Console.WriteLine(url);// Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpgApply common transformations like resizing, cropping, and format conversion:
usingImagekit;usingImagekit.Models;stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/path/to/image.jpg",Transformation=[newTransformation{Width=400,Height=300,Crop=Crop.MaintainRatio,Quality=80,Format=Format.Webp,},],});Console.WriteLine(url);// Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg?tr=w-400,h-300,q-80,c-maintain_ratio,f-webpAdd image overlays to your base image:
usingImagekit;usingImagekit.Models;stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/path/to/base-image.jpg",Transformation=[newTransformation{Width=500,Height=400,Overlay=newImageOverlay("/path/to/overlay-logo.png"){Position=newOverlayPosition{X="10",Y="10"},Transformation=[newTransformation{Width=100,Height=50}],},},],});Console.WriteLine(url);// Result: URL with image overlay positioned at x:10, y:10Add customized text overlays:
usingImagekit;usingImagekit.Models;stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/path/to/base-image.jpg",Transformation=[newTransformation{Width=600,Height=400,Overlay=newTextOverlay("Sample Text Overlay"){Position=newOverlayPosition{X="50",Y="50",Focus=Focus.Center},Transformation=[newTextOverlayTransformation{FontSize=40,FontFamily="Arial",FontColor="FFFFFF",Typography="b",// bold},],},},],});Console.WriteLine(url);// Result: URL with bold white Arial text overlay at center positionCombine multiple overlays for complex compositions:
usingImagekit;usingImagekit.Models;stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/path/to/base-image.jpg",Transformation=[newTransformation{Width=800,Height=600,Overlay=newTextOverlay("Header Text"){Position=newOverlayPosition{X="20",Y="20"},Transformation=[newTextOverlayTransformation{FontSize=30,FontColor="000000"},],},},newTransformation{Overlay=newImageOverlay("/watermark.png"){Position=newOverlayPosition{Focus=Focus.BottomRight},Transformation=[newTransformation{Width=100,Opacity=70}],},},],});Console.WriteLine(url);// Result: URL with text overlay at top-left and semi-transparent watermark at bottom-rightGenerate signed URLs that expire after a specified time for secure content delivery:
usingImagekit;usingImagekit.Models;// Generate a signed URL that expires in 1 hour (3600 seconds)stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/private/secure-image.jpg",Transformation=[newTransformation{Width=400,Height=300,Quality=90}],Signed=true,ExpiresIn=3600,// URL expires in 1 hour});Console.WriteLine(url);// Result: URL with signature parameters (?ik-t=timestamp&ik-s=signature)// Generate a signed URL that doesn't expirestringpermanentSignedUrl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/private/secure-image.jpg",Signed=true,// No ExpiresIn means the URL won't expire});Console.WriteLine(permanentSignedUrl);// Result: URL with signature parameter (?ik-s=signature)ImageKit frequently adds new transformation parameters that might not yet be documented in the SDK. You can use the Raw parameter to access these features or create custom transformation strings:
usingImagekit;usingImagekit.Models;stringurl=client.Helper.BuildUrl(newSrcOptions{UrlEndpoint="https://ik.imagekit.io/your_imagekit_id",Src="/path/to/image.jpg",Transformation=[newTransformation{Width=400,Height=300},newTransformation{Raw="something-new"},],});Console.WriteLine(url);// Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg?tr=w-400,h-300:something-newGenerate authentication parameters for secure client-side file uploads:
usingImagekit;ImageKitClientclient=new(){PrivateKey="private_key_xxx",};// Generate authentication parameters for client-side uploadsvarauthParams=client.Helper.GetAuthenticationParameters();Console.WriteLine(authParams);// Result: AuthenticationParameters { Token = "<uuid-token>", Expire = <timestamp>, Signature = "<hmac-signature>" }// Generate with custom token and expiry (seconds from now)varcustomAuthParams=client.Helper.GetAuthenticationParameters("my-custom-token",1800);Console.WriteLine(customAuthParams);// Result: AuthenticationParameters { Token = "my-custom-token", Expire = 1800, Signature = "<hmac-signature>" }These authentication parameters can be used in client-side upload forms to securely upload files without exposing your private API key.
For detailed information about webhook setup, signature verification, and handling different webhook events, refer to the ImageKit webhook documentation.
The SDK throws custom unchecked exception types:
ImageKitApiException: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:
| Status | Exception |
|---|---|
| 400 | ImageKitBadRequestException |
| 401 | ImageKitUnauthorizedException |
| 403 | ImageKitForbiddenException |
| 404 | ImageKitNotFoundException |
| 422 | ImageKitUnprocessableEntityException |
| 429 | ImageKitRateLimitException |
| 5xx | ImageKit5xxException |
| others | ImageKitUnexpectedStatusCodeException |
Additionally, all 4xx errors inherit from ImageKit4xxException.
ImageKitIOException: I/O networking errors.ImageKitInvalidDataException: Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.ImageKitException: Base class for all exceptions.
The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
Only the following error types are retried:
- Connection errors (for example, due to a network connectivity problem)
- 408 Request Timeout
- 409 Conflict
- 429 Rate Limit
- 5xx Internal
The API may also explicitly instruct the SDK to retry or not retry a request.
To set a custom number of retries, configure the client using the MaxRetries method:
usingImagekit;ImageKitClientclient=new(){MaxRetries=3};Or configure a single method call using WithOptions:
usingSystem;varresponse=awaitclient.WithOptions(options =>optionswith{MaxRetries=3}).Files.Upload(parameters);Console.WriteLine(response);Requests time out after 1 minute by default.
To set a custom timeout, configure the client using the Timeout option:
usingSystem;usingImagekit;ImageKitClientclient=new(){Timeout=TimeSpan.FromSeconds(42)};Or configure a single method call using WithOptions:
usingSystem;varresponse=awaitclient.WithOptions(options =>optionswith{Timeout=TimeSpan.FromSeconds(42)}).Files.Upload(parameters);Console.WriteLine(response);To route requests through a proxy, configure your client with a custom HttpClient:
usingSystem.Net;usingSystem.Net.Http;usingImagekit;varhttpClient=newHttpClient(newHttpClientHandler{Proxy=newWebProxy("https://example.com:8080")});ImageKitClientclient=new(){HttpClient=httpClient};The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.
To set undocumented parameters, a constructor exists that accepts dictionaries for additional header, query, and body values. If the method type doesn't support request bodies (e.g. GET requests), the constructor will only accept a header and query dictionary.
usingSystem.Collections.Generic;usingSystem.Text.Json;usingImagekit.Core;usingImagekit.Models.Files;FileUploadParamsparameters=new(rawHeaderData:newDictionary<string,JsonElement>(){{"Custom-Header",JsonSerializer.SerializeToElement(42)}},rawQueryData:newDictionary<string,JsonElement>(){{"custom_query_param",JsonSerializer.SerializeToElement(42)}},rawBodyData:newDictionary<string,MultipartJsonElement>(){{"custom_body_param",JsonSerializer.SerializeToElement(42)}}){// Documented properties can still be added here.// In case of conflict, these parameters take precedence over the custom parameters.Expire=0};The raw parameters can also be accessed through the RawHeaderData, RawQueryData, and RawBodyData (if available) properties.
This can also be used to set a documented parameter to an undocumented or not yet supported value, as long as the parameter is optional. If the parameter is required, omitting its init property will result in a compile-time error. To work around this, the FromRawUnchecked method can be used:
usingSystem.Collections.Generic;usingSystem.Text.Json;usingImagekit.Models.Files;varparameters=FileUploadParams.FromRawUnchecked(rawHeaderData:newDictionary<string,JsonElement>(),rawQueryData:newDictionary<string,JsonElement>(),rawBodyData:newDictionary<string,JsonElement>{{"file",JsonSerializer.SerializeToElement("custom value")}});Undocumented properties, or undocumented values of documented properties, on nested parameters can be set similarly, using a dictionary in the constructor of the nested parameter.
usingSystem.Collections.Generic;usingSystem.Text.Json;usingImagekit.Models.Files;FileUploadParamsparameters=new(){Transformation=new(newDictionary<string,JsonElement>{{"custom_nested_param",JsonSerializer.SerializeToElement(42)}})};Required properties on the nested parameter can also be changed or omitted using the FromRawUnchecked method:
usingSystem.Collections.Generic;usingSystem.Text.Json;usingImagekit.Models.Files;FileUploadParamsparameters=new(){Transformation=Transformation.FromRawUnchecked(newDictionary<string,JsonElement>{{"required_property",JsonSerializer.SerializeToElement("custom value")}})};To access undocumented response properties, the RawData property can be used:
usingSystem.Text.Json;varresponse=awaitclient.Files.Upload(parameters);if(response.RawData.TryGetValue("my_custom_key",outJsonElementvalue)){// Do something with `value`}RawData is a IReadonlyDictionary<string, JsonElement>. It holds the full data received from the API server.
In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a string, but the API could return something else.
By default, the SDK will not throw an exception in this case. It will throw ImageKitInvalidDataException only if you directly access the property.
If you would prefer to check that the response is completely well-typed upfront, then either call Validate:
varresponse=awaitclient.Files.Upload(parameters);response.Validate();Or configure the client using the ResponseValidation option:
usingImagekit;ImageKitClientclient=new(){ResponseValidation=true};Or configure a single method call using WithOptions:
usingSystem;varresponse=awaitclient.WithOptions(options =>optionswith{ResponseValidation=true}).Files.Upload(parameters);Console.WriteLine(response);This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
- Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
- Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an issue with questions, bugs, or suggestions.