Asp.net

帶有 Windows 身份驗證的 ASP.NET Web API 自託管

  • March 5, 2012

我正在嘗試將 ASP.NET Web API Self-Host 選項與 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();
           }
       }
   }
}

這是控制器:

[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;
   }
}

編輯 - 我添加了 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>

如果 Authorize 屬性被註釋掉,則Request.GetUserPrincipal().Identity.Name拋出空引用異常,因為Request.GetUserPrincipal()產生空值。

我也遇到了這個問題,我想出的唯一解決方案是提供專用的 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);
   }
}

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

var config = new NtlmSelfHostConfiguration("http://myComputerName:8080");

這種方法的唯一問題是,現在對使用此配置的伺服器發出的每個請求都需要進行身份驗證。

引用自:https://stackoverflow.com/questions/9571445