Giter Club home page Giter Club logo

hosting's Introduction

Hosting [Archived]

This GitHub project has been archived. Ongoing development on this project can be found in https://github.com/aspnet/AspNetCore and https://github.com/aspnet/Extensions.

The Hosting repo contains code required to host an ASP.NET Core application, it is the entry point used when self-hosting an application.

This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the AspNetCore repo.

hosting's People

Contributors

ajaybhargavb avatar analogrelay avatar aspnetci avatar benaadams avatar brennanconroy avatar bricelam avatar chengtian avatar cwe1ss avatar damianedwards avatar davidfowl avatar dougbu avatar eilon avatar glennc avatar grabyourpitchforks avatar halter73 avatar haok avatar javiercn avatar jkotalik avatar juntaoluo avatar kichalla avatar lodejard avatar loudej avatar mikeharder avatar natemcmaster avatar ntaylormullen avatar pakrym avatar pranavkm avatar ryanbrandenburg avatar tratcher avatar troydai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hosting's Issues

Async startup

We should allow middleware that does async stuff.

UserServices with IServiceProvider needs to register OptionAccessor explicitly

In the overloads of 'UseServices' method, the OptionsAccessor service is registered by default except the one that takes IServiceProvider. The error obtained when using the suggested method was not obvious and seems like should be either registered by default for it too or put at a place that is more visible.

Have consistent way to terminate server across platforms

I was trying to run ASP.NET web servers inside Docker containers using “k web” command, I realized that Microsoft.AspNet.Hosting waits for console input to terminate web server. (see this line https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/Program.cs#L90 )

This is preventing the process inside Docker container to terminate when no stdin is attached. (workaround: if I run the container with -i, it works fine since it attaches a stdin).

I suggest removing this behavior, it doesn’t make sense to terminate upon stdin input, users always have Ctrl+C option to terminate and by convention, server applications are designed to be daemons and should not be interacting with STDIN.

Should hosting expose the code used to set root HttpContext?

In WebFX we need to create a scoped service container if the RequestContainer middleware is not in use. To really do this with full fidelity we'd have to duplicate the code that sets HttpContext into the execution context. Should we expose an api for this that's used both in RequestContainer and WebFX?

ConfigureServices should support returning IServiceProvider

We overlooked the custom DI container scenario here:

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        var containerBuilder = new ContainerBuilder();
        containerBuilder.Populate(services);

        IContainer container = containerBuilder.Build();

        return container.Resolve<IServiceProvider>();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseServices();

        app.UseMvc();
    }
}

about permissions

Hi,
this is a quite generic question, because I don't have any running sample. Sometimes I have intranet applications that need additional permissions: the most common problem is to print in an installed printer in the server based on user input.
How can handle this? If I'm using self hosting I have to run the task using another user?

DI: Assigning proper scopes

Currently, most Services are configured to have transient scope. We need to redesign and assign proper scoping for better performance.

Services are defined in Microsoft.AspNet.Hosting.HostingServices

Need a way of excluding directories from compilation

We need some way of marking directories as "thou shalt not compile any .cs files you might find in here." This is to support scenarios where developers put their file upload directory under their app root.

This should be specified within the subdirectory itself rather than in some top-level .json file to avoid issues where the directory is renamed but the .json file is not updated. (We saw issues in ASP.NET where developers renamed directories without updating tags in top-level Web.config, and it opened security holes.)

Chunked encoding when formatters write out the response

I know that this is a known thing for a while now...but adding this bug however to keep track of this...
also the behavior is different from Helios in this matter...

When formatters write out the response on Helios, they are not sent out as chunked encoded, but they are in case of weblistener...

We need a higher layer of buffering which would provide consistent experience across different hosts...

More discussion over here: aspnet/HttpSysServer#61

Lifetime of Startup object should be documented

In 55271e8#diff-af9c739c5ded325b7930617398c74300L94 the app's Startup object is instantiated (assuming a non-static ConfigureXyz method) but it is not entirely clear the lifetime of this object. This came up during a customer app porting exercise from MVC 5 to MVC 6 where the customer has encountered issues in the past where developers on a project might cross some references between this object and other objects, thus perhaps preventing something from being GC'ed, or even affecting the stability of an app.

I looked at the code and couldn't immediately tell the lifetime of the object because it is contained in a lambda whose lifetime I am unsure of.

Catch selfhost Startup errors and show them in the browser

When anything goes wrong with Helios' startup code path it will catch those errors, finish starting the server, and send an error page in response to any HTTP requests.

When anything goes wrong with the Self-Host startup code path it will throw an exception and crash the process. If you're lucky the exception will be printed on the console, but even this requires setting the ASPNET_ENV to Development. This is even harder to debug in AppFabric or Azure Worker roles.

Proposal: Move/duplicate some of Helios' startup logic into the Hosting package. When errors occur locating the startup class/method or executing it, catch those and generate a default error page application instead.

There are only a small class of errors that would prevent the server from actually starting and serving such an error page (address conflicts, compiler errors, etc.), so we should be able to provide the error page for a range of common errors.

UseMiddleware DI activator can't find Invoke method if declared in base class

Microsoft.AspNet.RequestContainer.ContainerExtensions.UseMiddleware can be used to activate middleware types and inject dependencies. After activation It searches for the Invoke method by calling GetTypeInfo().GetDeclaredMethod("Invoke"). However, for the auth middleware (Cookies) Invoke is defined in the base class so this approach does not find it.

There are actually two alternatives available now:
(1) Portable to all platforms based on new reflection surface are:
http://msdn.microsoft.com/en-us/library/system.reflection.runtimereflectionextensions.getruntimemethods(v=vs.110).aspx
Note that this returns non-public methods as well. To get public only, filter by some means (loop, linq) on MethodInfo.IsPublic

(2) Available in K already and coming soon to a portable OOB library:
System.Reflection.CompatibilityExtensions.GetMethods (includes binding flags overloads, works just like the classic stuff).

No way to declaratively add middleware

I am working on porting Elmah to the k world. Elmah is Error logging module. It relies heavily on HTTP modules and Handlers. They can be replaced by Middleware in K world. But another feature it supports it pluggability. You can just drop the binary to your bin folder and add the lines for Modules and Handlers in the web.config. It starts working for unhandled exceptions. There is no way in the world to achieve this config-based addition of middleware. To get something like Elmah working, you will need to change the code to add a line in startup. Sometimes you may just have a website running with no source code available. You wont be able to plugin something like Elmah in the case.

ApplicationShutdown token may not fire for some shutdown scenarios

This is theoretical scenario (you know what it means - I don't have a repro)

For example:

public void Configure(IBuilder app)
{
   var applicationLifeTime = app.ApplicationServices.GetService<IApplicationLifetime>();
   applicationLifeTime.ApplicationStopping.Register(() =>
   {
      CleanUpResources();
    });
    applicationLifeTime.ApplicationStopped.Register(() =>
    {
      CleanUpRemainingResources();
    });

   //Middleware1
   app.UseMiddleware(typeof(MW1));

   //Middleware2
   app.UseMiddleware(typeof(MW2));
}

public class MW2
{
 public MW2(...)
 {
   throw UnhandledException();
 }
}

Today we trigger the application shutdown token only if the application start is fully successful. Consider the above scenario where one of the middleware constructors failed to secure a resource.

When the application pipeline is built - during the first pass both MW1 and MW2 are being added to a list. During the second pass when the app tries to instantiate MW1 & MW2 objects - when MW2 construction fails we don't trigger the application shutdown token because the application has not completely started. In the above case there is a chance the application can leak resources as the application shutdown token was not triggered.

Ask: Put the Configure method call around a try/catch block and attempt to trigger shutdown token even if the application did not fully start.

Startup method can be driven by running environment.

well-known terms include "Development", "Production", "Staging".
working assumption - environment value - e.g. SET web:Environment=Staging
determines which method name is found inside the startup class first, Configuration being the fallback.

Add an API for calling ConfigureServices

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
            // Configure and use scoped services for this request.
            app.UsePerRequestServices();
}

public void ConfigureServices(IServiceCollection services)
{
}

Create IHostingEnvironment and implementation

using System;

namespace Microsoft.AspNet.Hosting
{
    [AssemblyNeutral]
    public interface IHostingEnvironment 
    {
        string EnvironmentName { get; }
        string WebRoot { get; }
    }
}

This interface is the moral equivalent of the IApplicationEnvironment but for web applications. The environment name is the name of the currently running environment and the WebRoot is where the web sever is rooted.

Recognize and invoke Startup.ConfigureServices(IServiceCollection) if it exists

Making Startup.ConfigureServices first-class (as opposed to only an argument for app.UseServices() in Startup.Configure) allows separating other work that could happen as part of starting the application from the mere configuration of the DI container.

As long as the pattern is implemented correctly by the application this enables using the actual services configuration of the application (which could be customized) in design-time scenarios such as Migrations and Scaffolding, without incurring in the extra cost of starting up the whole application.

The contents of Startup can then look similar to this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFramework().AddSqlServer();
    services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>();

...
}

public void Configure(IApplicationBuilder app)
{
    app.UseErrorPage(ErrorPageOptions.ShowAll)
       .UseServices()
       .UseStaticFiles()
       .UseIdentity();
    DoSomethingExpensive();
...
}

Extend IHostingEnvironment to add WebRootFileSystem

This is part of the work to create a component that StaticFileMiddleware and FilePathResult can both use. IWebRootFileSystemProvider will be what the host sets. Higher level components will use IOptionsAccessors.

Has:

IFileSystem GetFileSystem();
string MapPath(string);

Startup sequence should throw if the Startup method isn't void-returning

We saw a scenario where somebody inadvertently wrote a Task-returning Startup method, and the runtime misbehaved since the method hadn't run to completion before the application was booted.

We should check the signature of the Startup method to make sure it's void-returning before we invoke it.

Startup auto-discovery

Startup.cs strategy change
any distinct class named Startup from the assembly may be used
application assembly name is known in new model, so hunting in all assemblies must not happen

Need the ability to select a specific Startup class

Right now StartupLoader hardcodes Startup and Configuration as the class and method names. This prevents us from specifying the Startup by name or generic type. Only discovery and lamda are currently supported.

Use cases:

  • WebApplication.Start<TStartup>
  • TestServer.Create<TStartup>
  • Command line or configuration parameter

Native modules shouldn't prevent managed middleware from running

UseStageMarker allows OWIN middleware to execute earlier in the IIS integrated pipeline, enabling middlewares to handle requests that would otherwise generate a 404 by the IIS StaticFile module.

Without this capability, paths that look like static content (e.g. foo.txt) cannot be handled by vNext apps running in IIS.

Is there an equivalent extension method to be used with IBuilder?

Application shutdown sequences

Relates to #18 and Helios

// provided by root-most layer, akin to IApplicationEnvironment
// dependency-injected into hosting layer to subscribe to shutdownrequested token
// dependency-injected into file watcher or other low-level components
// which have a reason to request process shutdown
IApplicationShutdown
{
  // called by subsystems that wish to initiate a graceful shutdown.
  // typical callers include file watcher
  // expect to return immediately.
  void RequestShutdown();

  // token triggered the first time RequestShutdown is called
  // typical observers include helios or self-host's "main" method
  // expected behavior is to return from "main" which will result in
  // the rest of the tear-down sequence occuring
  // including triggering IHttpApplicationLifecycle events
  // and ultimately process termination or recycling
  CancelationToken ShutdownRequested {get;}
}

// provided by web-hosting layer
// dependency-injected into frameworks or applications
// which have a reason to observe or delay the shutdown sequence
// the shutdown sequence cannot be cancelled
IApplicationLifetime
{
  // triggered by the web application host, either as a result of 
  // ShutdownRequested token being triggered, or some other intrinsic reason.
  // http requests may still be in flight when this token is triggered.
  // the host should wait for all event handlers to return before proceeding.
  CancelationToken ApplicationStopping {get;}

  // triggered by the web application host, either as a result of 
  // ShutdownRequested token being triggered, or some other intrinsic reason.
  // http requests will be entirely completed when this token is triggered.
  // the host should wait for all event handlers to return before proceeding.
  CancelationToken ApplicationStopped {get;}
}

inside Microsoft.AspNet.Hosting's Program.Main
the primary thread should block on a wait handle
the wait handle should be signalled by ShutdownRequested triggering
in a second thread there should be a call to Console.ReadLine()
and when Console.ReadLine() returns it should call RequestShutdown()

when the IDisposable returned by IHostingEngine.Start is Dispose()ed
it should immediately signal the ApplicationStopping token
then should call the weblistener server's idisposable dispose method
which should stop accepting requests if it hasn't already
and wait for all requests in flight to drain
and then return from the weblistener's disponse
then should signal ApplicationStopped token
then return from Dispose

In the Helios case, the IDisposable returned by IHostingEngine.Start should be Dispose()ed
it should immediately signal the ApplicationStopping token
then should call the helios' iserverfactory's start idisposable dispose method
which should stop accepting requests if it hasn't already
and wait for all requests in flight to drain
and then return from the iserverfactory.start's idisponsable.dispose
then should signal ApplicationStopped token
then return from Dispose

Hosting fails to read "wwwroot" if the project.json contains a JSON element that cannot be read by the JSON config source

We use the JsonConfiguration source to parse the project.json file to read wwwroot. When the project.json contains an JSON element that this configuration source cannot read it throws an exception and returns an incorrect wwwroot.

For example:
Have an authors element the project.json and wwwroot element. Hosting code here will fail to return the right wwwroot. It throws the following exception.
https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingUtilities.cs#L43


Add support for virtual root path when using TestHost

Scenario:
When writing in-memory functional tests for MVC, would like to cover link generation scenarios where an application could have virtual root path.

Workarounds:
Use mapping middleware in the application being tested. (I ideally would like to avoid this as it changes the application being tested and also if I want to change the virtual paths between tests, this does not give me the flexibility)

Code of interest:
https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.TestHost/ClientHandler.cs#L122

Bufferring middleware

When writing responses to a stream, a user or the MVC framework has to deal with buffering concerns. We should have a common middleware do deal with that.

The MVC template or UseMVC extension method can plug it in by default

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.