" System.Net.HttpListener"在IAppBuilder属性中不可用

时间:2017-05-25 19:02:50

标签: asp.net asp.net-web-api active-directory owin windows-authentication

我正在开发一个带有混合身份验证(基于Owin令牌和Windows身份验证)的Web应用程序。我已经实现了基于Owin令牌的身份验证,并希望为标记为活动目录用户的用户实现Windows身份验证。

在Owin中间件中,我想要请求用户的Windows用户名。我在OwinContext.Request.User.Identity中获得了对象。但是,OwinContext.Request.User.Identity.Name始终为空字符串。

我发现我应该在startup.cs中添加以下行:

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

但是,我得到密钥未找到异常。 " System.Net.HttpListener"属性数组中不存在。我已经安装了Microsoft.Owin.SelfHost,Microsoft.Owin.Host.HttpListener。但是,我仍然收到错误。

非常感谢任何帮助。

谢谢, GB

1 个答案:

答案 0 :(得分:0)

对我来说,问题是项目是作为共享库而不是Web应用程序启动的。

解决方案是在<ProjectGuid>行之后的 .cspro 文件中添加一行。

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

然后,您不需要显式添加HttpListener,只需重新加载项目并从Properties版开始就遵循此说明。 Enabling Windows Authentication in Katana

您可以通过相同的方式访问主体:

在OWIN中间件中获取用户:

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

    //...
}

在Web API控制器中获取用户:

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

UPD:List of Visual Studio Projects GUIDs