> Markdown version of https://tuna.am/en/docs/guides/install/sdk/dotnet/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# .NET

The .NET SDK opens Tuna tunnels straight from your code: expose a local HTTP or TCP service at a public address without installing `tuna`.

* `TunaTunnel.ForwardAsync` proxies connections from the public address to a local `host:port`.
* Survives network failures: reconnects and keeps the same public address.
* Dependencies are only [SSH.NET](https://github.com/sshnet/SSH.NET) and the standard library.

> **Info.** The API is not stable yet: it may change before v1.

The package is `Tuna.Sdk`, source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-dotnet).

## Installation

> **Code.tuna.am only for now.** The package will be on nuget.org a bit later. For now, add the `code.tuna.am` package registry as a NuGet source.

```shell
dotnet nuget add source https://code.tuna.am/api/packages/tuna/nuget/index.json --name tuna
dotnet add package Tuna.Sdk

```

The namespace is `Tuna.Sdk`. Requires .NET 8 or later.

## Authentication

Create an [API key](https://my.tuna.am/api_keys?lang=en) with **Run tunnels** enabled (the **For tunnels** preset) and pass it in `TunaOptions.ApiKey` or the `TUNA_API_KEY` environment variable.

## Forward to a local service

```csharp
using Tuna.Sdk;

var options = new TunaOptions
{
    Protocol = "http",
    OnEvent = e =>
    {
        if (e.Type == TunaEventType.Connected)
        {
            Console.WriteLine($"forwarding {e.Url} -> 127.0.0.1:5000");
        }
    },
};

await TunaTunnel.ForwardAsync(options, "127.0.0.1:5000", cancellationToken);

```

`ForwardAsync` runs until `cancellationToken` is cancelled or the tunnel ends for good. To get a tunnel object, start it with `StartAsync` and await `Completion`:

```csharp
await using var tunnel = await TunaTunnel.StartAsync(options, "127.0.0.1:5432");
Console.WriteLine(tunnel.Url);
await tunnel.Completion;

```

The local address is `host:port`. Unix sockets and `listen` mode are not supported.

## Options

| `TunaOptions` property    | Meaning                                                                                                                                                          |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Protocol`                | `http` or `tcp`, required                                                                                                                                        |
| `ApiKey`                  | API key, defaults to `$TUNA_API_KEY`                                                                                                                             |
| `Subdomain`, `Domain`     | HTTP: [reserved subdomain](https://tuna.am/en/docs/tunnels/http.md#reserved-subdomain) or [custom domain](https://tuna.am/en/docs/tunnels/http.md#custom-domain) |
| `Port`                    | TCP: [reserved port](https://tuna.am/en/docs/tunnels/ports.md) or its alias                                                                                      |
| `ProxyProtocol`           | TCP: [PROXY protocol](https://tuna.am/en/docs/tunnels/tcp.md#proxy-protocol) version, `1` or `2`                                                                 |
| `CidrAllow`, `CidrDeny`   | TCP: client subnets allowed or rejected by the Tuna node                                                                                                         |
| `OnEvent`                 | callback for tunnel events                                                                                                                                       |
| `ConnectTimeout`          | limit on the wait for the first connection; zero means no limit                                                                                                  |
| `ServerUrl`, `ClientName` | API address and client name reported to the server                                                                                                               |

## Events and errors

`OnEvent` receives `Connected`, `Reconnecting`, `Reconnected`, `Banner`, `SessionExpiring`, `Terminated` and `LocalError`. Calls never overlap and run on the tunnel's threads, so keep the callback short.

Network failures and temporary server errors are retried: the pause grows from 1 to 15 seconds with random jitter, and `Retry-After` is respected. If the connection to the node is lost, `Reconnecting` arrives after 15 seconds with a `KeepAliveTimeoutException`. The tunnel ends with an exception when retrying is pointless; check it with `TunaTunnel.IsPermanent`:

* `TunaServerException`: the API rejected the request — bad or revoked key, missing permission, unknown reserved name, unpaid plan. The details are in `Status`, `Code` and `RequestId`;
* `TunaTerminatedException`: the server closed the tunnel — it was deleted, suspended or hit the session time limit. The reason is in `Reason`.

## Behavior worth knowing

* The cancellation token passed to `StartAsync` or `ForwardAsync` bounds the whole life of the tunnel, not only the first connection. Cancelling it or disposing the tunnel closes all connections. To give up early when the tunnel does not come up, set `ConnectTimeout`.
* The `Host` header and the PROXY protocol header reach your service as sent.
* The API client is `HttpClient` and honors `HTTPS_PROXY`. Connections to Tuna nodes are plain SSH and do not use the proxy.
