具有Windows身份验证的ASP.NET Web API自主机

Dav*_*son 23 asp.net asp.net-mvc windows-authentication self-hosting asp.net-web-api

我试图使用ASP.NET Web API自我主机选项与Windows身份验证,以便我可以确定登录用户,并最终根据用户的身份接受或拒绝用户.这是我的控制台应用程序代码:

using System;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace SelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://myComputerName:8080");
            config.UseWindowsAuthentication = true;

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是控制器:

[Authorize]
public class HelloController : ApiController
{
    public string Get()
    {
        // This next line throws an null reference exception if the Authorize
        // attribute is commented out.
        string userName = Request.GetUserPrincipal().Identity.Name;
        return "Hello " + userName;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 我添加了Authorize属性,调试器显示从不调用Get操作方法中的代码.返回以下HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type></HEAD>
<BODY></BODY></HTML>
Run Code Online (Sandbox Code Playgroud)

如果注释掉Authorize属性,则Request.GetUserPrincipal().Identity.Name抛出空引用异常,因为Request.GetUserPrincipal()yield null.

tpe*_*zek 23

我也遇到了这个问题,我提出的唯一解决方案是提供专用的HttpSelfHostedConfiguration:

public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
{
    public NtlmSelfHostConfiguration(string baseAddress)
        : base(baseAddress)
    { }

    public NtlmSelfHostConfiguration(Uri baseAddress)
        : base(baseAddress)
    { }

    protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
    {
        httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
        httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
        return base.OnConfigureBinding(httpBinding);
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,您只需要更改一行(您不需要再设置UseWindowsAuthentication):

var config = new NtlmSelfHostConfiguration("http://myComputerName:8080");
Run Code Online (Sandbox Code Playgroud)

这种方法的唯一问题是,对使用此配置的服务器发出的每个请求现在都需要进行身份验证.