“System.Net.HttpListener” not available in IAppBui

2019-07-04 05:02发布

问题:

I am developing a web app with mix authentication (Owin Token Based and Windows authentication). I have implemented Owin token based authentication and want to implement windows authentication for the users which are marked as active directory users.

In Owin middleware, I want to get requesting user's windows username. I am getting object in OwinContext.Request.User.Identity. However, OwinContext.Request.User.Identity.Name is always blank string.

I found that I should add below lines in startup.cs:

var listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

However, I am getting key not found exception. "System.Net.HttpListener" is not present in Properties array. I have installed Microsoft.Owin.SelfHost, Microsoft.Owin.Host.HttpListener. However, I am still getting the error.

Any help is greatly appreciated.

Thanks, GB

回答1:

For me issue was that project was started as shared lib, not a web app.

Solution was to add a line into .cspro file after <ProjectGuid> line.

<ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Then you dont need to add HttpListener explicitly, just reload project and follow this instructions starting from Properties edition part. Enabling Windows Authentication in Katana

You can access principal the same ways:

Get the user in an OWIN middleware:

public async Task Invoke(IDictionary<string, object> env)
{
    OwinContext context = new OwinContext(env);
    WindowsPrincipal user = context.Request.User as WindowsPrincipal;

    //...
}

Get the user in a Web API Controller:

// In a web api controller function
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;

UPD: List of Visual Studio Projects GUIDs