Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scripting self hosted Web API with Roslyn CTP
#r "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Http.SelfHost.dll"
#r "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Newtonsoft.Json.4.5.6\lib\net40\Newtonsoft.Json.dll"
#r "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Http.dll"
#r "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.Formatting.dll"
#r "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.WebRequest.dll"
#r "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.dll"
#r "c:\Users\Filip\documents\visual studio 2012\Projects\Roslyn.WebApi\packages\Roslyn.Compilers.Common.1.2.20906.2\lib\net45\Roslyn.Compilers.dll"
#r "c:\users\filip\documents\visual studio 2012\Projects\Roslyn.WebApi\packages\Roslyn.Compilers.CSharp.1.2.20906.2\lib\net45\Roslyn.Compilers.CSharp.dll"
using System;
using System.IO;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Reflection;
using Roslyn.Compilers.CSharp;
using Roslyn.Compilers;
var text = @"
using System.Web.Http;
public class TestController : ApiController
{
public string Get() {
return ""Hello World"";
}
public string Get(int id) {
return ""Hello ""+id;
}
}";
//var tree = SyntaxTree.ParseText(text);
var tree = SyntaxTree.ParseFile(@"c:\Users\Filip\Documents\Visual Studio 2012\Projects\Roslyn.WebApi\Roslyn.WebApi\webapiScriptControllers.txt");
var compiledCode = Compilation.Create(
"controllers.dll",
options: new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] { tree },
references: new[] { new MetadataFileReference(typeof(object).Assembly.Location), new MetadataFileReference(@"C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Http.dll") });
Assembly assembly;
using (var stream = new MemoryStream())
{
EmitResult compileResult = compiledCode.Emit(stream);
assembly = Assembly.Load(stream.GetBuffer());
}
var address = "http://localhost:579";
var conf = new HttpSelfHostConfiguration(new Uri(address));
conf.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var server = new HttpSelfHostServer(conf);
server.OpenAsync().Wait();
Console.ReadKey();
using System.Web.Http;
public class TestController : ApiController
{
public string Get() {
return "Hello World";
}
public string Get(int id) {
return "Hello "+id;
}
};
public class DifferentController : ApiController
{
public string[] Get()
{
return new[] { "Hello World", "I'm a different controller" };
}
public string Get(int id)
{
return "Different " + id;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.