2012-10-20 47 views

回答

2

您示例中的用户名和密码使用HTTP基本验证 - 它们不是URL的一部分,而是包含在标题信息中。您可以访问ASP.NET中的此信息,请参阅此文章:Basic Authentication with Asp.Net WebAPI

public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute { 
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { 
     if (actionContext.Request.Headers.Authorization == null){ 
      // No Header Auth Info 
      actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 
     } else { 
      // Get the auth token 
      string authToken = actionContext.Request.Headers.Authorization.Parameter; 
      // Decode the token from BASE64 
      string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken)); 

      // Extract username and password from decoded token 
      string username = decodedToken.Substring(0, decodedToken.IndexOf(":")); 
      string password = decodedToken.Substring(decodedToken.IndexOf(":") + 1); 
     } 
    } 
} 
+0

这可能是一个愚蠢的问题。但是什么时候OnActionExecuting火灾? – Tom

+0

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting(v=vs.98).aspx - 它由Controller类中的每个Action方法调用。我的ASP.NET知识有点过时了,虽然我在很长一段时间里还没有用过它...... – doublesharp