FormsAuthentication是我没有通过用户,但我

时间:2012-11-20 20:45:24

标签: c# membership formsauthentication

我有这个登录方法:

   // POST: /Account/LogOn
    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl, string corpid)
    {
      var sb = new StringBuilder();
      sb.AppendLine("Logon HttpPost start");
      sb.AppendLine(string.Format("returnUrl: {0}", returnUrl));
      sb.AppendLine(string.Format("corpid: {0}", corpid));
      sb.AppendLine(string.Format("model.UserName: {0}", model.UserName));
      sb.AppendLine(string.Format("model.Password: {0}", model.Password));

      try
      {
        sb.AppendLine(string.Format("ModelState.IsValid: {0}", ModelState.IsValid));
        if (ModelState.IsValid)
        {
          if (Membership.ValidateUser(model.UserName, model.Password))
          {
            sb.AppendLine("Validated User");
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
                && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//")
                && !returnUrl.StartsWith("/\\"))
            {
              sb.AppendLine("Redirect(returnUrl)");
              return Redirect(returnUrl);
            }

            // need to decide whether to display the CustomerSummary, AccountScreen, or AddCustomer view
            // AccountScreen if they only have 1 account tied to this logon
            // AddCustomer if they do not havfe any tied to this logon
            // CustomerSummary if they have more than 1 tied to this logon

            var customers = _client.RequestCustomersForAccount(model.UserName);
            if (!customers.Any())
            {
              // no accounts tied to this logon
              sb.AppendLine("No accounts found for this login.");
              sb.AppendLine("RedirectToAction(AddCustomer, Customer)");
              return RedirectToAction("AddCustomer", "Customer");
            }

            if (customers.Count() == 1)
            {
              sb.AppendLine("1 accounts found for this login.");
              sb.AppendLine("RedirectToAction(AccountScreen, Customer)");
              model.AccountId = customers[0].AccountId;
              sb.AppendLine(string.Format("customers[0].AccountId: {0}", customers[0].AccountId));
              // only 1 account tied to this logon
              return RedirectToAction("AccountScreen", "Customer", model);
            }

            if (customers.Count() > 1)
            {
              sb.AppendLine(string.Format("{0} accounts found for this login.", customers.Count()));
              sb.AppendLine("RedirectToAction(CustomerSummary, Customer)");
              // no accounts tied to this logon
              return RedirectToAction("CustomerSummary", "Customer");
            }

          }
          else
          {
            var msg = "The user name or password provided is incorrect.";
            sb.AppendLine(msg);
            ModelState.AddModelError("", msg);
          }
        }

        // If we got this far, something failed, redisplay form
        return View(model);

      }
      catch (Exception ex)
      {
        sb.AppendLine(string.Format("An error occured: {0}", ex));
        WebPortalLogging.Logging.LogException("The following error occured: ", ex, _asName);
        return null;
      }
      finally
      {
        WebPortalLogging.Logging.LogInfo(sb.ToString(), _asName);
      }
    }

当我到达FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);行时,我收到此错误:

  

System.InvalidOperationException:未提供用户名。   在ClientCredentials中指定用户名。

     

服务器堆栈跟踪:at   System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement   tokenRequirement,Boolean disableInfoCard)at   System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvider(时间跨度   timeout,AuthenticationSchemes authenticationScheme,EndpointAddress   target,Uri via,ChannelParameterCollection channelParameters)at   System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvidersCore(的EndpointAddress   to,Uri via,ChannelParameterCollection channelParameters,TimeSpan   超时,SecurityTokenProviderContainer& tokenProvider,   SecurityTokenProviderContainer&安培; proxyTokenProvider)   System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.CreateAndOpenTokenProviders(时间跨度   超时)at   System.ServiceModel.Channels.HttpsChannelFactory.HttpsRequestChannel.OnOpen(时间跨度   超时)at   System.ServiceModel.Channels.CommunicationObject.Open(时间跨度   超时)at   System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
  在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan   超时)at   System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(时间跨度   超时,CallOnceManager级联)at   System.ServiceModel.Channels.ServiceChannel.EnsureOpened(时间跨度   System.ServiceModel.Channels.ServiceChannel.Call(String。)   action,Boolean oneway,ProxyOperationRuntime操作,Object [] ins,   对象[]出局,TimeSpan超时)at   System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage   methodCall,ProxyOperationRuntime operation)at   System.ServiceModel.Channels.ServiceChannelProxy.Invoke(即时聊天   消息)

     

在[0]处重新抛出异常:at   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(即时聊天   reqMsg,IMessage retMsg)at   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&安培;   msgData,Int32类型)at   SuburbanCustPortal.SuburbanService.ISuburbanService.RequestCustomersForAccount(字符串   customerloginname)at   SuburbanCustPortal.Controllers.AccountController.LogOn(LogOnModel   model,String returnUrl,String corpid)在C:\ work2 \ Doozer中   SOFTWARE \郊区\ SuburbanCustPortal \ \控制器AccountController.cs:行   112

此代码一次可以找到,我回过头来将它与我工作时的内容进行比较,除了记录已经改变之外我什么也看不到。

这是我添加的日志记录:

Logon HttpPost start
returnUrl: 
corpid: 
model.UserName: user
model.Password: password
ModelState.IsValid: True
Validated User
An error occured: System.InvalidOperationException: The username is not provided. Specify username in ClientCredentials.

Server stack trace: 
   at System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement, Boolean disableInfoCard)
   at System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme, EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
   at System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, SecurityTokenProviderContainer& tokenProvider, SecurityTokenProviderContainer& proxyTokenProvider)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.CreateAndOpenTokenProviders(TimeSpan timeout)
   at System.ServiceModel.Channels.HttpsChannelFactory.HttpsRequestChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
   at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at SuburbanCustPortal.SuburbanService.ISuburbanService.RequestCustomersForAccount(String customerloginname)
   at SuburbanCustPortal.Controllers.AccountController.LogOn(LogOnModel model, String returnUrl, String corpid) in C:\work2\Doozer Software\Suburban\SuburbanCustPortal\Controllers\AccountController.cs:line 112

正如您从日志中看到的那样,我通过了这个检查,我已经与用户一起登录了:

 if (Membership.ValidateUser(model.UserName, model.Password))

此外,我可以在我的计算机上本地运行此代码,并且我没有收到任何错误。这些都是针对同一个数据库,在本地发布。

有人知道我的问题是什么吗?

1 个答案:

答案 0 :(得分:0)

  

当我进入FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe)行时;我收到了这个错误:

您的堆栈跟踪显示该行引发异常:

var customers = _client.RequestCustomersForAccount(model.UserName);

大概这次调用失败了,因为你的Thread.CurrentPrincipal尚未设置为经过身份验证的用户(您设置了FormsAuthentication cookie,但在下一次请求之前不会处理它。)

我不确定您在验证用户后是否尝试执行其他工作,我建议您立即重定向,例如:

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
            && returnUrl.StartsWith("/")
            && !returnUrl.StartsWith("//")
            && !returnUrl.StartsWith("/\\"))
{
   sb.AppendLine("Redirect(returnUrl)");
   return Redirect(returnUrl);
}

Redirect(Request.UrlReferrer.ToString()); // Or wherever you want to redirect to