1

I was using the regular Microsoft asp webapi 2 to create a webservice. But to get rid of the IIS-Express I switched to use the owin-selfhost-package.

My only problem now is that I can't find the HTTPContext anymore.

in asp webapi 2 this worked.

HttpContext.Current.Session;

now

HttpContext.Current //is null

is null

i tried several suggestions from stackoverflow but non of them worked.

for example:

var context = HttpContext.Current.GetOwinContext(); //Current is null
var context2 = Request.GetOwinContext();            //Request is null
var context3 = HttpContext.GetOwinContext();        //GetOwinContext is no known method
var Session    = HttpContext.Current.Session;       //Current is null

what am I doing wrong?

UPDATE:

My Startup.cs

public class Startup
{
    private static readonly IUnityContainer _container = UnityHelpers.GetConfiguredContainer();

    public void Start()
    {
        UnityWebActivator.Start();
        var baseAddress = "http://localhost:10281/";
        var startupConfiguration = _container.Resolve<StartupConfiguration>();
        ConfigurationProvider.Init();

        // Start OWIN host
        using (WebApp.Start(baseAddress, startupConfiguration.Configuration))
        {
            Console.WriteLine("Host started and listens on {0}...", baseAddress);
            ////Create HttpCient and make a request to api/ values
            //var client = new HttpClient();

            //var response = client.GetAsync(baseAddress + "api/values").Result;

            //Console.WriteLine(response);
            //Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            Console.ReadLine();
            UnityWebActivator.Shutdown();
        }

    }
}

My StartupConfiguration.cs

public class StartupConfiguration
{
    private HttpConfiguration _config;

   public void Configuration(IAppBuilder appBuilder)
    {
        Console.WriteLine("Config started...");
        _config = new HttpConfiguration();

        // Add Unity filters provider
        RegisterFilterProviders(_config);

        ConfigureRoutes();
        ConfigureJsonSerialization();
        ConfigureFileSystemUse(appBuilder);


        appBuilder.UseWebApi(_config);

    }

   private static void RegisterFilterProviders(HttpConfiguration config)
   {
       config.DependencyResolver = new UnityDependencyResolver(UnityHelpers.GetConfiguredContainer());

       // Add Unity filters provider
       var providers = config.Services.GetFilterProviders().ToList();
       config.Services.Add(typeof(System.Web.Http.Filters.IFilterProvider), new WebApiUnityActionFilterProvider(UnityHelpers.GetConfiguredContainer()));
       var defaultprovider = providers.First(p => p is ActionDescriptorFilterProvider);
       config.Services.Remove(typeof(System.Web.Http.Filters.IFilterProvider), defaultprovider);
   }

    private void ConfigureRoutes()
    {
        _config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "{controller}/{id}", //routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );


        _config.MapHttpAttributeRoutes();
    }

    private void ConfigureJsonSerialization()
    {
        //JSon-Support
        _config.Formatters.Clear();
        _config.Formatters.Add(new JsonMediaTypeFormatter());
        _config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
    }

    private void ConfigureFileSystemUse(IAppBuilder appBuilder)
    {
        var directories = new List<string>
        {
            "web",
            "../../web",
            "../../../webservice/web"
        };

        var path = "";
        foreach (var directory in directories)
        {
            if (Directory.Exists(directory))
            {
                path = directory;
                break;
            }
        }

        var fileSystem = new PhysicalFileSystem(path);

        var options = new FileServerOptions
        {
            EnableDirectoryBrowsing = true,
            EnableDefaultFiles = true,
            DefaultFilesOptions = { DefaultFileNames = { "index.html" } },
            FileSystem = fileSystem,
            StaticFileOptions =
            {
                ServeUnknownFileTypes = true,
                FileSystem = fileSystem

            }
        };

        appBuilder.UseFileServer(options);
    }

}
Tobias Koller
  • 2,116
  • 4
  • 26
  • 46

1 Answers1

4

I finally found the solution for this Problem (thank you Robert!).

Follow the link Robert posted https://stackoverflow.com/a/27826059/2843504

Here is a copy of the linked Content:

Create These classes:

public class CurrentRequest
{
    public HttpRequestMessage Value { get; set; }
}

public class CurrentRequestHandler : DelegatingHandler
{
    protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var scope = request.GetDependencyScope();
        var currentRequest = (CurrentRequest)scope.GetService(typeof(CurrentRequest));
        currentRequest.Value = request;
        return await base.SendAsync(request, cancellationToken);
    }
}

Then you just need to register the DelegatingHandler with:

httpConfiguration.MessageHandlers.Insert(0, new CurrentRequestHandler());

And register the CurrentRequest and IOwinContext in the Container

container.RegisterType<CurrentRequest>(
            new HierarchicalLifetimeManager());

container.RegisterType<IOwinContext>(
    new HierarchicalLifetimeManager(),
    new InjectionFactory(c => c.Resolve<CurrentRequest>().Value.GetOwinContext()));

httpConfiguration.DependencyResolver = new UnityHierarchicalDependencyResolver(container);

Beside the custom delegation handler there are other places to hook into Web.API to capture the HttpRequestMessage for example you can create your own IHttpControllerActivator and use the ExecuteAsync method as described here: Dependency Injection in ASP.NET Web API 2

Community
  • 1
  • 1
Tobias Koller
  • 2,116
  • 4
  • 26
  • 46