Skip to content

Instantly share code, notes, and snippets.

@jijiechen
Created July 10, 2016 07:40
Show Gist options
  • Save jijiechen/afd1254aad99d3dee994a0846f94e05b to your computer and use it in GitHub Desktop.
Save jijiechen/afd1254aad99d3dee994a0846f94e05b to your computer and use it in GitHub Desktop.
Example code to demo default IHttpResponseFeature throwing System.NotImplementedException
using Xunit;
using MyNamespace;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Hosting;
using System.Threading.Tasks;
namespace MyNamespace.Tests
{
public class SampleTest
{
[Fact]
public async Task should_handle_request(){
var testServer = new MyTestServer();
var host = Startup.ConfigureHost(new WebHostBuilder()).UseServer(testServer).Build();
host.Start();
var httpContext = new DefaultHttpContext(){ RequestServices = host.Services };
httpContext.Request.Path = "/not-found";
await testServer.RequestHandler.Invoke(httpContext);
}
}
class MyTestServer : IServer
{
RequestDelegate _requestHandler;
public RequestDelegate RequestHandler { get { return _requestHandler; } }
public IFeatureCollection Features { get; } = new FeatureCollection();
public void Start<TContext>(IHttpApplication<TContext> application)
{
var webApplication = application as HostingApplication;
_requestHandler = async httpContext => {
var context = new HostingApplication.Context { HttpContext = httpContext };
await webApplication.ProcessRequestAsync(context);
};
}
public void Dispose()
{
_requestHandler = null;
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using Microsoft.AspNetCore.Http;
namespace MyNamespace
{
public class Startup
{
public static void Main(string[] args)
{
var host = ConfigureHost(new WebHostBuilder()).Build();
host.Run();
}
public static IWebHostBuilder ConfigureHost(IWebHostBuilder hostBuilder){
return hostBuilder.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel()
.UseStartup<Startup>();
}
// ConfigureServices is invoked before Configure
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddMvc();
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/signin"),
AccessDeniedPath = new PathString("/access-denied"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseStaticFiles();
app.UseMvc();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment