does "dotnet script" (csx) support ASP.NET Core app development?

536 views Asked by At

I am checking out "dotnet script" (csx) available here: https://github.com/filipw/dotnet-script

I am able to get basic examples working fine. However, I am trying to check the possibility of ASP.NET Core using "dotnet script" (just using plain csx).

main.csx:

#r "netcoreapp3.1\Microsoft.AspNetCore.dll" 
#r "netcoreapp3.1\Microsoft.AspNetCore.Hosting.dll" 
#r "netcoreapp3.1\Microsoft.Extensions.DependencyInjection.dll" 
#r "netcoreapp3.1\Microsoft.Extensions.Hosting.dll"
#load "Startup.csx"

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

CreateHostBuilder(null).Build().Run();

Startup.csx:

#r "netcoreapp3.1\Microsoft.AspNetCore.Diagnostics.dll" 
#r "netcoreapp3.1\Microsoft.AspNetCore.Hosting.dll" 
#r "netcoreapp3.1\Microsoft.AspNetCore.Http.dll" 
#r "netcoreapp3.1\Microsoft.Extensions.DependencyInjection.dll" 
#r "netcoreapp3.1\Microsoft.Extensions.Hosting.dll" 

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        });
    }
}

And I experience the following error:

System.BadImageFormatException: Could not load file or assembly 'Microsoft.Extensions.Hosting, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (0x80131058)
File name: 'Microsoft.Extensions.Hosting, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' ---> System.BadImageFormatException: Could not load file or assembly 'Microsoft.Extensions.Hosting, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL'. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (0x80131058)
File name: 'Microsoft.Extensions.Hosting, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL' ---> System.BadImageFormatException: Cannot load a reference assembly for execution.
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at System.Reflection.Assembly.LoadFromResolveHandler(Object sender, ResolveEventArgs args)
   at System.Runtime.Loader.AssemblyLoadContext.InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, String name)
   at System.Runtime.Loader.AssemblyLoadContext.OnAssemblyResolve(RuntimeAssembly assembly, String assemblyFullName)
   at Submission#0.CreateHostBuilder(String[] args)
   at Submission#0.<<Initialize>>d__0.MoveNext() in C:\temp\sample01\main.csx:line 51
--- End of stack trace from previous location ---
   at Dotnet.Script.Core.ScriptRunner.Execute[TReturn](String dllPath, IEnumerable`1 commandLineArgs) in /private/var/folders/6j/4hkjjhd50fg27s933nctz0480000gn/T/tmp3iI6tV/Dotnet.Script.Core/ScriptRunner.cs:line 52

Any idea on what I am doing wrong?

Thanks.

1

There are 1 answers

0
Rudomitori On

There is an example of using dotnet-script with custom SDK. It uses minimal API

#r "sdk:Microsoft.NET.Sdk.Web"

using Microsoft.AspNetCore.Builder;

var a = WebApplication.Create();
a.MapGet("/", () => "Hello world");
a.Run();

And one example from me:

// http-server.csx
#r "sdk:Microsoft.NET.Sdk.Web"

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;

// dotnet-script passes CLI arguments in var `Args` with type `IList<string>`.
// This differs from behaviour of Top-level statements, 
// so we need convert it to string[] 
// to use CLI args as in examples of minimal API
var args = Args.ToArray();

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

// I needed to serve files in the same directory that the script was placed
// but UseStaticFiles and UseDefaultFiles use `wwwroot` folder by default
var physicalFileProvider = new PhysicalFileProvider(builder.Environment.ContentRootPath);

app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = physicalFileProvider });
app.UseStaticFiles(new StaticFileOptions { FileProvider = physicalFileProvider });

app.Run();

You can run this code on port 8080 with following command:

dotnet script http-server.csx --urls http://localhost:8080