我正在尝试将 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()
产生空值。