0

我有这个登录方法:

   // 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 中指定用户名。

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

在 [0] 处重新引发异常:在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) 在 SuburbanCustPortal.SuburbanService 的 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)。 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

这段代码一次就可以找到,我回过头来将它与它工作时的代码进行比较,除了日志记录发生了变化,我没有看到任何其他内容。

这是我添加的日志记录:

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))

此外,我可以在本地计算机上运行此代码,并且不会出错。这一切都针对同一个数据库,本地和发布。

有人看到我的问题是什么吗?

4

1 回答 1

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
于 2012-11-20T21:21:37.070 回答