如何修复我的控制器使我的对象不为空

时间:2019-04-05 10:45:18

标签: c# asp.net-mvc

我想在我的MVC项目中使用fullcalendar。我的项目包括EWS API Exchange。我想得到约会。我也在使用广告身份验证:Configure ASP.NET MVC for authentication against AD

我创建了一个用户模型:

 public class AccountModels
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

然后使用AccountController:

     public ActionResult Login()
    {
        return View();
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(AccountModels model, string returnURL)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (this.Url.IsLocalUrl(returnURL) && returnURL.Length > 1 && returnURL.StartsWith("/")
                && !returnURL.StartsWith("//") && !returnURL.StartsWith("/\\"))
            {
                return this.Redirect(returnURL);
            }
            return this.RedirectToAction("Index", "Home", model);
        }

        this.ModelState.AddModelError(string.Empty, "The username or password is incorrect");

        return this.View(model);
    }

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();
        return this.RedirectToAction("Account", "Login");
    }

}

模型创建很好,然后使用Home方法重定向到Index控制器。在Index方法中,我创建了ExchnageServer,但是在完成Index之后,我的模型对象变为空。

此家庭控制器

    public ActionResult Index(AccountModels model)
    {
        ServerExchangeCore server = new ServerExchangeCore(model);
        return View(server);

    }

   // [Authorize]
    public JsonResult GetAppointments(ServerExchangeCore serverExchange)
    {
        ServerExchangeCore server = serverExchange;
        server.SetServer();
        JsonResult result = new JsonResult();
        List<Appointment> dataList = server.GetAppointments();
        result = Json(dataList, JsonRequestBehavior.AllowGet);
        return result;
    }

这是我的ServerExchnageCore

public class ServerExchangeCore
{
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2016);
    AccountModels _model = new AccountModels();
    public ServerExchangeCore()
    { }
    public ServerExchangeCore(AccountModels model)
    {
        _model = model;
    }

    public void SetServer()
    {
        string email = GetEmail()
        service.Credentials = new WebCredentials(_model.UserName, _model.Password);
        service.AutodiscoverUrl(email, RedirectionUrlValidationCallback);

    }


    public List<Appointment> GetAppointments()
    {
        DateTime startDate = DateTime.Now;
        string sssssss = service.Url.ToString();
        DateTime endDate = startDate.AddDays(30);
        CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
        CalendarView calendarView = new CalendarView(startDate, endDate);
        calendarView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
        FindItemsResults<Appointment> appointments = calendar.FindAppointments(calendarView);
        List<Appointment> lst = new List<Appointment>();
        foreach (Appointment aa in appointments)
        {
            lst.Add(aa);
        }
        return lst;
    }

    private string GetEmail()
    {

        if (HttpContext.Current.User.Identity.Name != null && HttpContext.Current.User.Identity.IsAuthenticated)
        {

            MembershipUser user = Membership.GetUser();
            if (user != null)
                userEmail = user.Email;
        }
        userEmail = Membership.GetUser().Email;
        return userEmail;
    }

如何修复我的Home控制器?

2 个答案:

答案 0 :(得分:0)

我找到了更好的解决方案https://blogs.msdn.microsoft.com/emeamsgdev/2012/11/05/ews-from-a-web-application-using-windows-authentication-and-impersonation/,请尝试使用它。仍然了解如何获取电子邮件地址。

答案 1 :(得分:0)

我使用Kerberos作为链接https://blogs.msdn.microsoft.com/emeamsgdev/2012/11/05/ews-from-a-web-application-using-windows-authentication-and-impersonation/

对其进行了解析

//创建用户帐户

        IIdentity id = HttpContext.Current.User.Identity;
        id = Thread.CurrentPrincipal.Identity;
        id = WindowsIdentity.GetCurrent();
        string email = GetEmail(id);
        service.Credentials = new WebCredentials(CredentialCache.DefaultCredentials);

然后尝试获取用户的电子邮件地址

      private string GetEmail(IIdentity id)
    {
        System.DirectoryServices.ActiveDirectory.Domain domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();
        string address = String.Empty;
        using (HostingEnvironment.Impersonate())
        {
            using (var context = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
            using (var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, id.Name))
            {
                address = userPrincipal.EmailAddress;
            }
        }
        return address;
    }