If you just want a simple http server in your add-in, I don't need
ASP.NET and can just use the HttpListener class that is part of the core runtime.
Code for this might be:
using System.Net;
using System;
using ExcelDna.Integration;
namespace TestAspNetInExcel
{
public class AddIn : IExcelAddIn
{
public static object SayHello() => "Hello from ExcelDna with
ASP.NET!";
public void AutoOpen()
{
Task.Run(() => StartHttpListener());
}
public void AutoClose()
{
}
async void StartHttpListener()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("
http://localhost:8000/");
listener.Start();
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
HttpListenerResponse response = context.Response;
string responseString = "<html><body>Hello, World!</body></html>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
await output.WriteAsync(buffer, 0, buffer.Length);
output.Close();
}
}
}
}
Using more of the
ASP.NET functionality won't work at the moment, because of the way Excel-DNA is setting up the runtime loading.
When loading the runtime for the first time, we create a fresh .runtimeconfig.json that just loads the "
Microsoft.WindowsDesktop.App" framework.
Excel-DNA could be enhanced to add this as an option when loading the runtime, though it would only work if this add-in is the first one to load into Excel.
I'm not sure that's the right approach though, given that the Excel process might need to host various add-ins.
If you only need a bit more help than the basic HttpListener support, you might look at one of the lightweight wrappers around HttpListener that would just add a library or two to your add-in.
If you really need full
ASP.NET support, we would need to make some changes on the Excel-DNA side.
-Govert