Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2012
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. ASP.NET Web API Self-Host with Windows Authentication
  2. using System;
  3. using System.Web.Http;
  4. using System.Web.Http.SelfHost;
  5.  
  6. namespace SelfHost
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. var config = new HttpSelfHostConfiguration("http://myComputerName:8080");
  13. config.UseWindowsAuthentication = true;
  14.  
  15. config.Routes.MapHttpRoute(
  16. "API Default", "api/{controller}/{id}",
  17. new { id = RouteParameter.Optional });
  18.  
  19. using (HttpSelfHostServer server = new HttpSelfHostServer(config))
  20. {
  21. server.OpenAsync().Wait();
  22.  
  23. Console.WriteLine("Press Enter to quit.");
  24. Console.ReadLine();
  25. }
  26. }
  27. }
  28. }
  29.  
  30. [Authorize]
  31. public class HelloController : ApiController
  32. {
  33. public string Get()
  34. {
  35. // This next line throws an null reference exception if the Authorize
  36. // attribute is commented out.
  37. string userName = Request.GetUserPrincipal().Identity.Name;
  38. return "Hello " + userName;
  39. }
  40. }
  41.  
  42. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  43. <HTML><HEAD>
  44. <META content="text/html; charset=windows-1252" http-equiv=Content-Type></HEAD>
  45. <BODY></BODY></HTML>
  46.  
  47. public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
  48. {
  49. public NtlmSelfHostConfiguration(string baseAddress)
  50. : base(baseAddress)
  51. { }
  52.  
  53. public NtlmSelfHostConfiguration(Uri baseAddress)
  54. : base(baseAddress)
  55. { }
  56.  
  57. protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
  58. {
  59. httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
  60. httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
  61. return base.OnConfigureBinding(httpBinding);
  62. }
  63. }
  64.  
  65. var config = new NtlmSelfHostConfiguration("http://myComputerName:8080");
  66.  
  67. using System.Web.Http;
  68. public class MyAuth : AuthorizeAttribute
  69. {
  70. public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
  71. {
  72. base.OnAuthorization(actionContext); //put breakpoint here
  73. }
  74. }
  75.  
  76. [Authorize]
  77. public class HelloController : ApiController
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement