Crestapps core aspnet hosting

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core aspnet hosting is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for composing CrestApps.Core 2.0 into ASP.NET Core MVC, Razor Pages, Blazor Web App, Minimal API, and .NET MAUI hybrid hosts. Covers Program.cs ordering, AddCrestAppsCore with a store and commit filters, middleware order (UseWebSockets before UseRouting, UseAIAnonymousVisitorCookie, rate limit

How to use this skill

Skill file

CrestApps.Core ASP.NET Hosting

You are a CrestApps.Core expert. Register host services first, compose CrestApps through AddCrestAppsCore(...), then map only the hubs and endpoints for the features the host enables.

Rules

MVC Program.cs

using CrestApps.Core;
using CrestApps.Core.AI;
using CrestApps.Core.AI.Chat;
using CrestApps.Core.AI.Chat.AGUI;
using CrestApps.Core.AI.Documents;
using CrestApps.Core.AI.Documents.Endpoints;
using CrestApps.Core.AI.Documents.OpenXml;
using CrestApps.Core.AI.Documents.Pdf;
using CrestApps.Core.AI.OpenAI;
using CrestApps.Core.Data.EntityCore;
using CrestApps.Core.SignalR;
using MyApp.Hubs;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddLocalization();
builder.Services.AddControllersWithViews()
    .AddCrestAppsStoreCommitterFilter();
builder.Services.AddHttpContextAccessor();

Directory.CreateDirectory(Path.Combine(builder.Environment.ContentRootPath, "App_Data"));

builder.Services.AddCrestAppsCore(crestApps => crestApps
    .AddAISuite(ai => ai
        .AddEntityCoreStores()
        .AddOpenAI()
        .AddChatInteractions(chat => chat
            .AddEntityCoreStores()
            .ConfigureChatHubOptions<ChatInteractionHub>())
        .AddDocumentProcessing(documents => documents
            .AddEntityCoreStores()
            .AddOpenXml()
            .AddPdf())
        .AddSignalR(addStoreCommitterFilter: true))
    .AddIndexingServices(indexing => indexing.AddEntityCoreStores())
    .AddEntityCoreSqliteDataStore(
        $"Data Source={Path.Combine(builder.Environment.ContentRootPath, "App_Data", "crestapps.db")}"));

builder.Services.ConfigureCrestAppsChatHubOptions<AIChatHub>();

var app = builder.Build();

await app.Services.InitializeEntityCoreSchemaAsync();

app.UseHttpsRedirection()
    .UseStaticFiles()
    .UseWebSockets()
    .UseRouting()
    .UseAIAnonymousVisitorCookie()
    .UseAuthentication()
    .UseAuthorization();

app.MapHub<AIChatHub>("/hubs/ai-chat");
app.MapHub<ChatInteractionHub>("/hubs/chat-interaction");

// Optional: other AG-UI clients over HTTP (see crestapps-core-ag-ui).
app.MapAGUIChat<AIChatHub>()
    .RequireAuthorization();

app.AddDownloadAIDocumentEndpoint();
app.AddDownloadAIDocumentFigureEndpoint();
app.AddDownloadKnowledgeFigureEndpoint();
app.AddUploadChatInteractionDocumentEndpoint();
app.AddRemoveChatInteractionDocumentEndpoint();
app.AddUploadChatSessionDocumentEndpoint();
app.AddRemoveChatSessionDocumentEndpoint();

app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

await app.RunAsync();

For YesSql, swap the store calls for .AddYesSqlStores() and .AddYesSqlDataStore(configuration => configuration.UseSqLite(...)), then create the index tables before serving requests (see crestapps-core-yessql-stores).

Chat Hubs

The packages ship hub base classes; the host owns the concrete hub, its route and its authorization.

using CrestApps.Core.AI.Chat.Hubs;
using CrestApps.Core.AI.Models;
using Microsoft.AspNetCore.Authorization;

namespace MyApp.Hubs;

[AllowAnonymous]
public sealed class AIChatHub : AIChatHubCore<IAIChatHubClient>
{
    public AIChatHub(IServiceProvider services, TimeProvider timeProvider, ILogger<AIChatHub> logger)
        : base(services, timeProvider, logger)
    {
    }

    protected override Task<bool> AuthorizeProfileAsync(IServiceProvider services, AIProfile profile)
    {
        return Task.FromResult(Context.User?.Identity?.IsAuthenticated == true);
    }
}

[Authorize]
public sealed class ChatInteractionHub : ChatInteractionHubBase
{
    public ChatInteractionHub(IServiceProvider services, TimeProvider timeProvider, ILogger<ChatInteractionHub> logger)
        : base(services, timeProvider, logger)
    {
    }
}

.AddSignalR(...) on the AI suite calls AddCoreSignalR(pathPrefix), which registers HubRouteManager, sets host-wide MaximumParallelInvocationsPerClient = 8 and StreamBufferCapacity = 64, and switches the JSON protocol to camelCase. Hub-level overrides and route management are covered in crestapps-core-signalr; realtime voice in crestapps-core-realtime-voice.

For speech-to-speech over WebRTC, also call builder.Services.AddWebRtcRealtimeTransport() (package CrestApps.Core.AI.WebRTC). It binds ICE servers from CrestApps:AI:RealtimeTransport; the browser falls back to WebSocket when WebRTC is unavailable.

Document Endpoint Authorization

| Endpoint extension | Route | Requirement and resource |

|---|---|---|

| AddDownloadAIDocumentEndpoint() | GET ai/documents/{documentId}/download | AIChatDocumentOperations.ManageDocuments on ChatInteraction, AIProfile, or AIChatSessionDocumentAuthorizationContext |

| AddDownloadAIDocumentFigureEndpoint() | GET ai/documents/{documentId}/figures/{figureId} | same as above |

| AddDownloadKnowledgeFigureEndpoint() | GET ai/knowledge/{dataSourceId}/figures/{canonicalId} | AIKnowledgeOperations.ViewFigures on AIDataSource |

| AddUploadChatInteractionDocumentEndpoint(), AddRemoveChatInteractionDocumentEndpoint() | POST ai/chat-interactions/upload-document, .../remove-document | ManageDocuments on ChatInteraction |

| AddUploadChatSessionDocumentEndpoint(), AddRemoveChatSessionDocumentEndpoint() | POST ai/chat-sessions/upload-document, .../remove-document | ManageDocuments on AIChatSessionDocumentAuthorizationContext |

using CrestApps.Core.AI.Documents;
using CrestApps.Core.AI.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;

namespace MyApp.Security;

public sealed class ChatInteractionDocumentAuthorizationHandler
    : AuthorizationHandler<OperationAuthorizationRequirement, ChatInteraction>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        OperationAuthorizationRequirement requirement,
        ChatInteraction resource)
    {
        if (resource is not null &&
            requirement.Name == AIChatDocumentOperations.ManageDocuments.Name &&
            context.User.IsInRole("Administrator"))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}
builder.Services.AddScoped<IAuthorizationHandler, ChatInteractionDocumentAuthorizationHandler>();

Write one handler per resource type the host serves, using whatever rule decides who may use that profile, interaction, session or data source.

Other Application Models

Chat UI Assets

The chat scripts and styles (ai-chat.js, ai-chat-widget.js, chat-interaction.js, chat-markers.js, realtime-audio.js, ai-chat.css, chat-widget.css, and others) ship in the npm package @crestapps/ai-chat-ui. The sample hosts serve the same files from the CrestApps.AI.Resources project as /_content/CrestApps.AI.Resources/scripts/... and /styles/...; that Razor class library is not published to NuGet, so a package-based host serves the npm build from its own wwwroot.

Live Site-Settings Options

When admin-managed settings feed options (for example DefaultAIDeploymentSettings, GeneralAIOptions, PromptSecurityOptions), consume IOptionsMonitor<TOptions> and register an IOptionsChangeTokenSource<TOptions> that fires when the settings store saves. The samples do this with SiteSettingsStore and SiteSettingsOptionsChangeTokenSource<TOptions>; copy the pattern rather than the sample types.

Sample-Host Code, Not Package APIs

Do not tell users to call these from a package; they live in src/Startup and must be copied or rewritten: AddSharedSampleHostDefaults(), AddSharedSiteSettings(...), AddMvcSampleHostServices(...), AddBlazorSampleHostServices(...), AddSharedAIChatProtection(), UseSharedAIChatProtection(), AddA2AHost(), MapA2AHost(), AddChatApiEndpoints(), InitializeYesSqlSchemaAsync(), SeedArticlesAsync(), and SampleHostContentRootResolver. InitializeEntityCoreSchemaAsync(), ConfigureCrestAppsChatHubOptions<THub>(), UseAIAnonymousVisitorCookie(), AddWebRtcRealtimeTransport(), MapAGUIChat<THub>() and the Add*Endpoint() document extensions are package APIs. See crestapps-core-sample-hosts.

Upgrading Within 2.0 Previews

Upgrading from 1.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.