C# / .NET SDK & ASP.NET Core
The official .NET SDK gives you the LifeAstroAPI endpoints as async methods in 23 resource
groups, with the same method names as the Node.js SDK in PascalCase plus Async (Node's
dasha.char is Dasha.CharAsync). It runs on .NET 8, 9 and 10, in ASP.NET Core, and on
.NET Framework 4.6.2 and later: the package targets net8.0 and netstandard2.0.
LifeAstroApi: the client. Its only dependency isSystem.Text.Json, which .NET 8 already has.LifeAstroApi.Extensions.DependencyInjection:services.AddLifeAstro(...)registers one sharedLifeAstroClientfromappsettings.json, sending its requests throughIHttpClientFactory.- On NuGet: LifeAstroApi and LifeAstroApi.Extensions.DependencyInjection.
- Source and full README: github.com/ayanshulife/lifeastroapi-dotnet.
Install
.NET CLI:
dotnet add package LifeAstroApi --version 1.3.0Or in the .csproj:
<PackageReference Include="LifeAstroApi" Version="1.3.0" />In an ASP.NET Core application, add the dependency injection package instead; it brings
LifeAstroApi with it (see ASP.NET Core):
dotnet add package LifeAstroApi.Extensions.DependencyInjection --version 1.3.0<PackageReference Include="LifeAstroApi.Extensions.DependencyInjection" Version="1.3.0" />First call
using System.Text.Json;
using LifeAstroApi;
using LifeAstroApi.Params;
using var client = new LifeAstroClient(new LifeAstroClientOptions
{
ApiKey = "dv_live_...", // or leave it out and set LIFEASTRO_API_KEY
});
// Today's panchang in Mumbai, in Gujarati
JsonElement day = await client.Panchang.BasicAsync(
new PanchangBasicParams(19.076, 72.8777, "Asia/Kolkata") { Lang = Lang.Gu });
Console.WriteLine(day.GetProperty("tithi").GetProperty("name").GetString()); // e.g. સપ્તમી
// A Vedic birth chart
var arjun = new BirthInput("1990-01-15", "10:30", "Asia/Kolkata", 19.076, 72.8777);
JsonElement chart = await client.Chart.PlanetsAsync(new ChartPlanetsParams(arjun));
// Kundli matching (Ashtakoota, 36 points)
var girl = new BirthInput("1992-06-20", "14:15", "Asia/Kolkata", 28.6139, 77.209);
JsonElement match = await client.Milan.AshtakootaAsync(new MilanAshtakootaParams(arjun, girl) { Lang = Lang.Hi });
Console.WriteLine($"{match.GetProperty("total").GetDouble()} / 36");The client is immutable and thread-safe: create one and share it across the application (a
static field or a DI singleton); it keeps its HTTP connections open between calls. It is
IDisposable: dispose it when the application stops. Creating a client per request wastes sockets.
The API key (dv_live_…) is sent as an Authorization: Bearer … header. Give it to the options, or
set the LIFEASTRO_API_KEY environment variable and leave ApiKey out:
new LifeAstroClient(new LifeAstroClientOptions { ApiKey = "dv_live_..." }); // 1. explicit
new LifeAstroClient("dv_live_..."); // 2. shorthand
new LifeAstroClient(); // 3. reads LIFEASTRO_API_KEYKeep the key on your server: load it from an environment variable, user secrets or a secrets manager, never from source code, and never ship it inside a MAUI, WPF, WinForms, Unity or Blazor WebAssembly app. Apps call your own backend, which calls LifeAstroAPI with this SDK.
Parameters
Every method takes a parameter object named after it: client.Panchang.BasicAsync(...) takes
PanchangBasicParams, client.Western.Natal.ChartAsync(...) takes WesternNatalChartParams. They
are in the LifeAstroApi.Params namespace. Required values are constructor parameters, checked at
once (ArgumentException when one is empty); optional values are properties you set with an object
initializer.
var p = new PanchangBasicParams(19.076, 72.8777, "Asia/Kolkata") // or new PanchangBasicParams(new Place(...))
{
Date = new DateTime(2027, 1, 15), // or "2027-01-15", a DateTimeOffset or a DateOnly; defaults to today in tz
Time = "06:30", // or a TimeSpan, DateTime or TimeOnly
Lang = Lang.Gu,
Ayanamsa = Ayanamsa.Krishnamurti,
};new BirthInput(date, time, tz, lat, lon)is the chart input. It takes strings and numbers, orDateTime/DateOnlyandTimeSpan/TimeOnly, for example the columns of your own entity.new BirthInput(date, time, place)takes aPlace.- The SDK sends each value under the name the API reads, exactly as the Node.js SDK does:
unprefixed
date/time/tz/lat/lonfor a chart,birth.*for the natal chart of transit-style methods,boy.*/girl.*for kundli matching,personA.*/personB.*for Western pairs. - Moment methods (
Panchang,Muhurta,Prashna) send today's date in the giventzwhenDateis left out. - All dates, times and numbers are formatted with the invariant culture, whatever
CultureInfo.CurrentCultureis. p.ToQuery()shows the exact query a parameter object sends andp.ToString()the path and query string (handy as a cache key). A parameter object is not thread-safe while you set it; build one per call.- A method whose parameters are all optional can be called without them:
client.Transit.PositionsAsync(),client.Meta.VersionAsync().
Each method returns the response JSON as a JsonElement. The generic overload maps it to your own
type with System.Text.Json:
public sealed class Tithi { public int Index { get; set; } public string? Name { get; set; } public string? Paksha { get; set; } }
public sealed class Basic { public Tithi? Tithi { get; set; } public string? SunriseLocal { get; set; } }
Basic? basic = await client.Panchang.BasicAsync<Basic>(p);The default options read the API's snake_case names into PascalCase properties (sunrise_local →
SunriseLocal), match case-insensitively and ignore properties your class does not have, so your
classes only need the fields you use.
Languages
Every Vedic method whose response carries names or text takes an optional Lang. The same fields
come back in that language; ids, dates and numbers do not change. All ten languages are complete.
JsonElement day = await client.Panchang.BasicAsync(new PanchangBasicParams(new Place(19.076, 72.8777, "Asia/Kolkata"))
{
Date = "2027-01-15",
Lang = Lang.Gu, // tithi, nakshatra, yoga, karana and vara names in Gujarati
});Lang | Code | Language |
|---|---|---|
Lang.En | en | English (default) |
Lang.Hi | hi | Hindi |
Lang.Mr | mr | Marathi |
Lang.Gu | gu | Gujarati |
Lang.Bn | bn | Bengali |
Lang.Te | te | Telugu |
Lang.Ta | ta | Tamil |
Lang.Kn | kn | Kannada |
Lang.Ml | ml | Malayalam |
Lang.Pa | pa | Punjabi |
- The SDK sends it as
langandlocale(the API reads either).LangExtensions.FromCode("gu")turns a code into the enum andLang.Gu.ToCode()back. - Methods that return only times, numbers or ids, such as
Panchang.RahuKaalAsync,Chart.YogasAsyncandTransit.WindowsAsync, have noLangproperty. Western,Tarot,GeoandMetaanswer in English.Western.NarrativetakesLangforEn,HiandMr.
ASP.NET Core
Add LifeAstroApi.Extensions.DependencyInjection. It registers one LifeAstroClient (a singleton)
from your configuration, sending its requests through IHttpClientFactory:
// appsettings.json: the key itself goes in user secrets or an environment variable (LifeAstroApi__ApiKey)
{
"LifeAstroApi": {
"BaseUrl": "https://api.lifeastroapi.com",
"Timeout": "00:00:30",
"MaxRetries": 2
}
}using LifeAstroApi;
using LifeAstroApi.Params;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLifeAstro(builder.Configuration.GetSection("LifeAstroApi"));
// or in code: builder.Services.AddLifeAstro(o => o.ApiKey = builder.Configuration["LifeAstro:Key"]);
var app = builder.Build();
app.MapGet("/panchang/today", (double lat, double lon, string tz, LifeAstroClient astro, CancellationToken ct) =>
astro.Panchang.BasicAsync(new PanchangBasicParams(lat, lon, tz) { Lang = Lang.Gu }, cancellationToken: ct));
app.Run();Or inject it into a controller:
[ApiController]
[Route("api/kundli")]
public sealed class KundliController : ControllerBase
{
private readonly LifeAstroClient _astro;
public KundliController(LifeAstroClient astro) => _astro = astro;
[HttpPost]
public async Task<IActionResult> Chart(BirthRequest r, [FromQuery] string lang = "en", CancellationToken ct = default)
{
var birth = new BirthInput(r.Date, r.Time, r.Tz, r.Lat, r.Lon);
JsonElement chart = await _astro.Chart.PlanetsAsync(
new ChartPlanetsParams(birth) { Lang = LangExtensions.FromCode(lang) }, cancellationToken: ct);
return Ok(chart);
}
}
public sealed record BirthRequest(string Date, string Time, string Tz, double Lat, double Lon);ApiKey,BaseUrl,Timeout,MaxRetriesandDefaultHeadersbind from the section. Without anApiKeythe client readsLIFEASTRO_API_KEY; without either, resolving the client throws anInvalidOperationExceptionthat says so.AddLifeAstro(section, o => o.OnResponse = ...)adds settings that configuration cannot hold, such as a hook.- The named
HttpClient("LifeAstroApi") recycles pooled connections every 5 minutes, so DNS changes are picked up even though the client is a singleton. The SDK already retries; do not stack another retry policy on top. - Registration uses
TryAdd: aLifeAstroClientyou register yourself wins.
Entity Framework Core
The SDK does not touch your database; it calls the API and returns JSON. Keep the birth details in your own entity and turn them into the SDK's input:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = "";
public DateOnly BirthDate { get; set; } // date column (EF Core 8+); DateTime works too
public TimeOnly BirthTime { get; set; } // time column; TimeSpan works too
public string BirthTimeZone { get; set; } = "Asia/Kolkata"; // IANA id
public double BirthLat { get; set; }
public double BirthLon { get; set; }
public BirthInput ToBirthInput() => new BirthInput(BirthDate, BirthTime, BirthTimeZone, BirthLat, BirthLon);
}public async Task<JsonElement> BirthChartAsync(int customerId, Lang lang, CancellationToken ct)
{
Customer c = await _db.Customers.AsNoTracking().SingleAsync(x => x.Id == customerId, ct);
return await _astro.Chart.PlanetsAsync(new ChartPlanetsParams(c.ToBirthInput()) { Lang = lang }, cancellationToken: ct);
}Cache what is shared, for example today's panchang per city: it is the same for every user. A
parameter object's ToString() is its path and query, including today's date in the place's time
zone, so it makes a key that changes at local midnight:
public Task<JsonElement> TodayAsync(Place city, Lang lang, CancellationToken ct)
{
var p = new PanchangBasicParams(city) { Lang = lang };
return _cache.GetOrCreateAsync(p.ToString(), entry => // IMemoryCache
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6);
return _astro.Panchang.BasicAsync(p, cancellationToken: ct);
});
}Save a report's JSON if you need it again; showing it later costs no credits:
public class SavedReport
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string Kind { get; set; } = ""; // "kundli-lite"
public string Lang { get; set; } = ""; // "gu"
public string Json { get; set; } = "";
public DateTimeOffset CreatedAt { get; set; }
}
// OnModelCreating: jsonb on PostgreSQL (Npgsql), nvarchar(max) on SQL Server
modelBuilder.Entity<SavedReport>().Property(r => r.Json).HasColumnType("jsonb"); // or "nvarchar(max)"public async Task<SavedReport> SaveKundliReportAsync(int customerId, Lang lang, CancellationToken ct)
{
Customer c = await _db.Customers.SingleAsync(x => x.Id == customerId, ct);
JsonElement report = await _astro.Reports.KundliLiteAsync(
new ReportsKundliLiteParams(c.ToBirthInput()) { Name = c.Name, Lang = lang }, cancellationToken: ct);
var saved = new SavedReport
{
CustomerId = c.Id, Kind = "kundli-lite", Lang = lang.ToCode(), Json = report.GetRawText(), CreatedAt = DateTimeOffset.UtcNow,
};
_db.SavedReports.Add(saved);
await _db.SaveChangesAsync(ct);
return saved;
}Read it back with JsonDocument.Parse(saved.Json) or
JsonSerializer.Deserialize<MyReport>(saved.Json, LifeAstroJson.DefaultOptions).
Async and cancellation
Every method is async and takes a CancellationToken:
JsonElement chart = await client.Chart.PlanetsAsync(new ChartPlanetsParams(arjun), cancellationToken: ct);A cancelled token throws OperationCanceledException at once and is never retried. In ASP.NET Core
pass HttpContext.RequestAborted (or the CancellationToken parameter of a minimal API handler) so
an abandoned request stops its API call. There are no synchronous methods; in code that cannot be
async, block on the task with client.Panchang.BasicAsync(p).GetAwaiter().GetResult(), but prefer
async all the way.
Errors, retries and credits
Every non-2xx response throws an exception carrying the API's error Code, the HTTP Status and
the RequestId:
try
{
await client.Chart.PlanetsAsync(p);
}
catch (PaymentRequiredException)
{
// 402: out of credits, or the trial is used up
}
catch (RateLimitException e)
{
TimeSpan? wait = e.RetryAfter; // from Retry-After, may be null
}
catch (LifeAstroException e)
{
logger.LogError("{Status} {Code} {Message} (request {RequestId})", e.Status, e.Code, e.Message, e.RequestId);
}| Exception | When |
|---|---|
BadRequestException | 400: a parameter is missing, malformed or out of range |
AuthenticationException | 401: missing or invalid API key |
PaymentRequiredException | 402: out of credits |
PermissionException | 403: the key may not make this call (plan, IP allow-list) |
NotFoundException | 404: unknown path or id |
RateLimitException | 429: rate limit or daily quota; RetryAfter |
ServerException | 5xx |
LifeAstroConnectionException | no HTTP response: DNS, refused or reset connection, TLS |
LifeAstroTimeoutException | the call took longer than the timeout; it extends LifeAstroConnectionException, so catch it first |
All extend LifeAstroException. 408, 425, 429, 500, 502, 503, 504, network errors and timeouts are
retried automatically (2 times by default, MaxRetries), honouring Retry-After. Other 4xx are not
retried. Failed calls are free.
OnResponse reports your credit balance, rate limit and request id, for every call (client options)
or for one call (RequestOptions):
using var client = new LifeAstroClient(new LifeAstroClientOptions
{
OnResponse = info =>
{
if (info.CreditsRemaining < 5_000)
{
logger.LogWarning("LifeAstroAPI credits low: {Credits}", info.CreditsRemaining);
}
},
});
await client.Panchang.BasicAsync(p, new RequestOptions
{
OnResponse = info => logger.LogDebug("{RequestId} {RateLimit}", info.RequestId, info.RateLimit),
});The hook runs once per call with the final response, success or error. CreditsRemaining is the
balance after the call (unchanged after a failed call); an exception thrown inside the hook is
ignored, so logging can never break a call.
.NET Framework
The package's netstandard2.0 build runs on .NET Framework 4.6.2 and later (4.7.2+ recommended: it
needs no binding redirects for the netstandard facades), in ASP.NET MVC 5, Web API 2, WebForms, WCF,
Windows services and desktop apps. Every API works from C# 7.3, the default language version of
.NET Framework projects.
-
TLS 1.2.
api.lifeastroapi.comaccepts TLS 1.2 and later. .NET Framework 4.7+ uses the operating system's defaults; on 4.6.2 turn TLS 1.2 on once at startup (inApplication_StartorMain):ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; -
One client for the application, in a static field or your DI container, not one per request.
-
Synchronous code:
client.Panchang.BasicAsync(p).GetAwaiter().GetResult(); preferasync Task<ActionResult>actions. -
"Today" in a time zone: when you leave
Dateout of a moment method, the SDK sends today's date in the method'stz. The SDK maps the common IANA ids (Asia/Kolkata,Asia/Dubai,Europe/London,America/New_York, ...) to Windows time zones itself; UTC offsets such as+05:30work everywhere. For a zone it cannot resolve, setDateyourself.
Reports
client.Reports returns each report (kundli lite, detailed and brihad, match making, mangal dosha,
sade sati, varshaphal, numerology, horoscopes) as one JSON document in the requested language, ready
for your own template or to store and show again without spending credits.