Skip to content

Application Configuration

TIP

The easiest way to get started with Coalesce is to use the Coalesce project template, which includes all the necessary configuration out of the box.

Basic Setup

For Coalesce to work in your application, you must register the needed services in your Program.cs. Doing so is simple:

c#
// Program.cs
builder.Services.AddCoalesce<AppDbContext>();

Advanced Configuration

This registers all the basic services that Coalesce needs to work with your EF DbContext. However, many more options are available. Here's a more complete invocation of AddCoalesce that takes advantage of many of the options available:

c#
// Program.cs
builder.Services.AddCoalesce(b => b
    .AddContext<AppDbContext>()
    .UseDefaultDataSource(typeof(MyDataSource<,>))
    .UseDefaultBehaviors(typeof(MyBehaviors<,>))
    .UseTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"))
    .Configure(o =>
    {
        o.ValidateAttributesForMethods = true; // note: true is the default
        o.ValidateAttributesForSaves = true; // note: true is the default
        o.DetailedExceptionMessages = true;
        o.ExceptionResponseFactory = ctx =>
        {
            if (ctx.Exception is FileNotFoundException)
            {
                ctx.HttpContext.Response.StatusCode = 404; // Optional - set a specific response code.
                return new IntelliTect.Coalesce.Models.ApiResult(false, "File not found");
            }
            return null;
        };
    })
);

Builder Methods

Available builder methods include:

public Builder AddContext<TDbContext>()

Register services needed by Coalesce to use the specified context. This is done automatically when calling the services.AddCoalesce<AppDbContext>(); overload.

public Builder UseDefaultDataSource(Type dataSource)

Overrides the default data source used, replacing the Standard Data Source. See Data Sources for more details.

public Builder UseDefaultBehaviors(Type behaviors)

Overrides the default behaviors used, replacing the Standard Behaviors. See Behaviors for more details.

public Builder UseTimeZone(TimeZoneInfo timeZone)

Specify a static time zone that should be used when Coalesce is performing operations on dates/times that lack timezone information. For example, when a user inputs a search term that contains only a date, Coalesce needs to know which timezone's midnight to use when performing the search.

public Builder UseTimeZone<ITimeZoneResolver>()

Specify a service implementation to use to resolve the current timezone. This should be a scoped service, and will be automatically registered if it is not already. This allows retrieving timezone information on a per-request basis from HTTP headers, Cookies, or any other source.

public Builder Configure(Action<CoalesceOptions> setupAction)

Configure additional options for Coalesce runtime behavior. Current options include options for server-side validation, and options for exception handling. See individual members for details.

Middleware & Helpers

Coalesce provides several helper extension methods to simplify common application setup tasks:

public static IApplicationBuilder UseViteStaticFiles(this IApplicationBuilder app, ViteStaticFilesOptions? options = null)

Configures static file middleware with optimizations for Vite build output. This middleware:

  • Serves static files from wwwroot
  • Applies long-term caching (30 days) to files with cache-busting hashes in their filenames (as produced by Vite)
  • Supports optional authorization and response customization hooks

This calls UseStaticFiles internally, so it should be used in place of, not in addition to, a call to UseStaticFiles. If you need more advanced control, you should instead use UseStaticFiles directly.

c#
app.UseViteStaticFiles();
c#
// With custom authorization:
app.UseViteStaticFiles(new()
{
    OnAuthorizeAsync = ctx => ctx.Context.Request.Path.StartsWithSegments("/assets") == true
        // Vite compiled assets require authentication
        ? ValueTask.FromResult(ctx.Context.User.Identity?.IsAuthenticated == true)
        // Anything else (e.g. `src/public` directory) do not.
        : ValueTask.FromResult(true)
});

public static IApplicationBuilder UseNoCacheResponseHeader(this IApplicationBuilder app)

Adds a Cache-Control: no-cache, no-store header to all responses that reach this point in the pipeline. This middleware acts as a pre-hook, so the resulting Cache-Control header can be overridden by other middleware or individual endpoints.

This is useful for preventing browsers from unexpectedly caching API responses. Usually this is placed just after .UseViteStaticFiles().

c#
app.UseNoCacheResponseHeader();

public static IEndpointConventionBuilder MapCoalesceSecurityOverview(this IEndpointRouteBuilder builder, string pattern)

Maps a route that presents an HTML page with a comprehensive overview of all types exposed by Coalesce and their effective security rules. This page displays:

  • Class-level security attributes ([Read], [Create], [Edit], [Delete])
  • Property-level security and restrictions
  • Custom data sources and behaviors
  • Method security rules
  • Service endpoints

See the Security Overview documentation for more details.

c#
app.MapCoalesceSecurityOverview("coalesce-security")
    .RequireAuthorization(new AuthorizeAttribute { Roles = "Admin" });

Coalesce is a free and open-source framework created by IntelliTect to fill our desire to create better apps, faster. IntelliTect is a high-end software architecture and development consulting firm based in Spokane, Washington.

If you're looking for help with your software project, whether it be a Coalesce application, other technologies, or even just an idea, reach out to us at info@intellitect.com — we'd love to start a conversation! Our clients range from Fortune 100 companies to local small businesses and non-profits.