ASP.NET Web APIセルフホストオプションをWindows認証で使用しようとしています。これにより、ログオンしているユーザーを特定し、最終的にユーザーのIDに基づいてユーザーを承認または拒否できます。これが私のコンソールアプリケーションコードです:
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属性を追加しましたが、デバッガーはGetactionメソッド内のコードが呼び出されないことを示しています。次の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属性がコメント化されている場合、 nullが生成さRequest.GetUserPrincipal().Identity.Nameれるため、null参照例外がスローされRequest.GetUserPrincipal()ます。