0

I have to serve a static website (multiple files) in an application written in .NET Framework 4.7. On the target system, the application cannot have admin privileges, so IIS is not an option.

I understand, that ASP.NET is the part of the framework supporting this, but how do I implement a static web server with it?

I don't even need anything special, like authentication or TLS, because the client will be on the same host.

I know this would be much easier with .NET 7, but this is not an option for me.

Corbie
  • 819
  • 9
  • 31
  • You only need admin if you are accessing the IIS resources like the file system. Put any files on a network drive where you can set access to anybody. There is no different between Net 4.7 and Net 7 with privileges. Net 7 you are using a runtime library. When you install an application on anther machine you always have to publish and install the setup.exe file even a IIS. With Net 7 there is a runtime library that gets installed when you publish. The Net/Core libraries have to be the same on build machine and deploy machine, or you need to publish. – jdweng Apr 08 '23 at 07:50

1 Answers1

1

You can setup a simple HttpListener to just serve files out of a folder.

Here is a simple proof of concept:

async Task ServeStaticWebSite() {
    var listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:60000/");
    listener.Start();
    const string baseDir = @"C:\tmp"; // where your files are, for example index.html

    while(true)  // keeps running forever, add some mechanism to stop this
    {
        var ctx =  await listener.GetContextAsync();
       
        // sanitize the url, verify no path traversal is possible 
        var fullPath = Path.GetFullPath(Path.Combine(baseDir, "." + ctx.Request.RawUrl.Replace('/', '\\')));
        
        if (File.Exists(fullPath)) {
            using(var fs = File.OpenRead(fullPath))
            {
               ctx.Response.StatusCode = 200;
               fs.CopyTo(ctx.Response.OutputStream);
            }
        } else {
            ctx.Response.StatusCode = 404;
        }
        ctx.Response.OutputStream.Close();
    }
    listener.Stop();
    listener.Close();
}

If you need to handle more connections in parallel extend my example with the solution in this answer on Handling multiple requests with C# HttpListener from user gordy

When the above method runs, you should get a result in your browser when you go to http://localhost:60000/index.html

rene
  • 41,474
  • 78
  • 114
  • 152
  • Thank you, I knew there has to be an easy way. One thing: I have added the line `ctx.Response.ContentType = System.Web.MimeMapping.GetMimeMapping(fullPath);` to the success response, so that the MIME type is set correctly. – Corbie Apr 11 '23 at 10:49