3

I'm developing an ASP.NET Core project and I'm trying to do dynamic routing, so if I go to /page/[str] it returns something custom depending on [str]. I can return a string like so:

app.MapGet("/page/name:alpha", (string name) => {
    return name;
});

Is there a way to render a cshtml and cshtml.cs file?

I looked at the ASP.NET Core but I couldn't find anything about this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Minimal APIs are designed for APIs, which means they return data. If you're looking to return HTML, you might want to stick with controllers. – gunr2171 Apr 01 '22 at 19:02
  • @gunr2171 how would I do dynamic routing with a controller? Not just /page, but /page/[str]? – Nikhil Nayak Apr 01 '22 at 20:20
  • https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0 – gunr2171 Apr 01 '22 at 20:21

1 Answers1

1

If you just want to return HTML you can define an HtmlResult like this:

using System.Net.Mime;
using System.Text;

internal class HtmlResult : IResult
{
    private readonly string _html;

    public HtmlResult(string html)
    {
        _html = html;
    }

    public Task ExecuteAsync(HttpContext httpContext)
    {
        httpContext.Response.ContentType = MediaTypeNames.Text.Html;
        httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(_html);
        return httpContext.Response.WriteAsync(_html);
    }
}

internal static class ResultsExtensions
{
    public static IResult Html(this IResultExtensions resultExtensions, string html)
    {
        ArgumentNullException.ThrowIfNull(resultExtensions);

        return new HtmlResult(html);
    }
}

And then use it like this:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/html", () => Results.Extensions.Html(@$"<!doctype html>
<html>
    <head><title>miniHTML</title></head>
    <body>
        <h1>Hello World</h1>
        <p>The time on the server is {DateTime.Now:O}</p>
    </body>
</html>"));

app.Run();
ctyar
  • 931
  • 2
  • 10
  • 22