Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc GetExternalLoginInfoAsync返回空MVC_Asp.net Mvc_Visual Studio_Azure - Fatal编程技术网

Asp.net mvc GetExternalLoginInfoAsync返回空MVC

Asp.net mvc GetExternalLoginInfoAsync返回空MVC,asp.net-mvc,visual-studio,azure,Asp.net Mvc,Visual Studio,Azure,尝试使用Microsoft AD从localhost运行MVC应用程序时,我收到以下代码错误。调试应用程序时,我注意到GetExternalLoginInfoAsync返回null。但是,该应用程序在web上运行良好。我错过了什么?谁来帮忙。我已经在错误消息下面发布了我的代码 “/”应用程序中出现服务器错误 对象引用未设置为对象的实例。 描述:执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源 异常详细信息:System.NullReferen

尝试使用Microsoft AD从localhost运行MVC应用程序时,我收到以下代码错误。调试应用程序时,我注意到GetExternalLoginInfoAsync返回null。但是,该应用程序在web上运行良好。我错过了什么?谁来帮忙。我已经在错误消息下面发布了我的代码


“/”应用程序中出现服务器错误

对象引用未设置为对象的实例。 描述:执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例

源错误:

第140行:{ 第141行:ExternalLoginInfo loginInfo=wait AuthenticationManager.getexternallogininfosync(); 第142行:ClaimsIdentity ClaimsIdentity=loginInfo.ExternalIdentity; 第143行:ApplicationUser ApplicationUser=新的ApplicationUser(索赔实体)

第144行:IdentityResult结果=等待UserManager.PersistAsync(applicationUser); 我的代码:
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.EntityFramework;
使用Microsoft.AspNet.Identity.Owin;
使用Microsoft.Owin.Security;
使用Microsoft.Owin.Security.Cookies;
使用Microsoft.Owin.Security.OpenIdConnect;
使用SampleQuoteTracker.Models;
使用制度;
使用System.Security.Claims;
使用System.Threading.Tasks;
使用System.Web;
使用System.Web.Mvc;
使用System.Web.Routing;
命名空间SampleQuoteTracker.Controllers
{
/// 
///提供接受和解除帐户身份验证以及创建新帐户的方法。
/// 
公共类AccountController:控制器
{
//
//获取:/Account/登录
公共操作结果登录(字符串返回URL)
{
ViewBag.Title=“登录”;
LoginViewModel LoginViewModel=新LoginViewModel()
{
ReturnUrl=ReturnUrl
};
返回视图(loginViewModel);
}
//
//POST:/帐户/登录
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务登录(LoginViewModel模型)
{
//最优种子返回目标
AjaxResultModel loginResult=新的AjaxResultModel
{
Status=“Valid”,
ReturnUrl=GetLocalUrl(model.ReturnUrl),
消息=null
};
if(Request.IsAjaxRequest())
{
如果(!ModelState.IsValid)
{
loginResult.Status=“无效”;
loginResult.Message=Tools.ListModelStateErrors(ModelState);
}
如果(loginResult.Status==“有效”)
{
SignInStatus结果=等待SignInManager.PasswordSignInAsync(
模型。电子邮件,
型号,密码,
记住,
shouldLockout:false);
开关(结果)
{
案例标志状态成功:
loginResult.Status=“成功”;
打破
案例标志状态锁定输出:
loginResult.Status=“锁定”;
loginResult.Message=AlertMessages.AccountLockOut;
打破
案例信号状态故障:
违约:
loginResult.Status=“失败”;
loginResult.Message=AlertMessages.AuthenticationFailure;
打破
}
}
}
返回Json(loginResult);
}
//
//POST:/帐户/注销
[授权]
[HttpPost]
[ValidateAntiForgeryToken]
公共行动结果注销()
{
//AuthenticationManager.SignOut();
//返回重定向操作(“SignOutCallback”);
返回null;
}
公共无效登录(字符串returnUrl=“/”)
{
如果(返回URL==“/”)
{
returnUrl=Request.ApplicationPath;
}
URIBaseUri=newUriBuilder(Request.Url.Scheme,Request.Url.Host,Request.Url.Port).Uri;
Uri=新Uri(baseUri,returnUrl);
//如果调用此操作且用户已通过身份验证,
//这意味着用户不是的适当角色的成员
//请求的控制器/操作。
如果(请求已验证)
{
RouteValueDictionary值=RouteDataContext.RouteValuesFromUri(uri);
字符串控制器名称=(字符串)值[“控制器”];
字符串actionName=(字符串)值[“action”];
string errorUrl=Url.Action(“错误”,
路线价值:新
{
message=“您无权查看此内容”,
控制器名称,
actionName
});
重定向(errorUrl,true);
}
其他的
{
// https://stackoverflow.com/a/21234614
//在登录前激活会话以正确生成身份验证cookie。
会话[“解决方法”]=0;
//发送OpenID连接登录请求。
字符串externalLoginCallback=Url.Action(“externalLoginCallback”,“Account”,new{ReturnUrl=ReturnUrl});
质询(新的AuthenticationProperties{RedirectUri=externalLoginCallback},
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using SampleQuoteTracker.Models;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;


namespace SampleQuoteTracker.Controllers
{
    /// <summary>
    /// Provides methods for accepting and desplaying account authenication and creating new accounts.
    /// </summary>
    public class AccountController : Controller
    {
        //
        // GET: /Account/Login
        public ActionResult Login(string returnUrl)
        {
            ViewBag.Title = "Log In";
            LoginViewModel loginViewModel = new LoginViewModel()
            {
                ReturnUrl = returnUrl
            };
            return View(loginViewModel);
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> Login(LoginViewModel model)
        {
            // seed return object optimistically
            AjaxResultModel loginResult = new AjaxResultModel
            {
                Status = "Valid",
                ReturnUrl = GetLocalUrl(model.ReturnUrl),
                Message = null
            };
            if (Request.IsAjaxRequest())
            {
                if (!ModelState.IsValid)
                {
                    loginResult.Status = "Invalid";
                    loginResult.Message = Tools.ListModelStateErrors(ModelState);
                }
                if (loginResult.Status == "Valid")
                {
                    SignInStatus result = await SignInManager.PasswordSignInAsync(
                        model.Email,
                        model.Password,
                        model.RememberMe,
                        shouldLockout: false);
                    switch (result)
                    {
                        case SignInStatus.Success:
                            loginResult.Status = "Success";
                            break;
                        case SignInStatus.LockedOut:
                            loginResult.Status = "LockOut";
                            loginResult.Message = AlertMessages.AccountLockOut;
                            break;
                        case SignInStatus.Failure:
                        default:
                            loginResult.Status = "Failure";
                            loginResult.Message = AlertMessages.AuthenticationFailure;
                            break;
                    }
                }
            }
            return Json(loginResult);
        }

        //
        // POST: /Account/LogOff
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //AuthenticationManager.SignOut();
            //return RedirectToAction("SignOutCallback");
            return null;
        }

        public void SignIn(string returnUrl = "/")
        {
            if (returnUrl == "/")
            {
                returnUrl = Request.ApplicationPath;
            }
            Uri baseUri = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port).Uri;
            Uri uri = new Uri(baseUri, returnUrl);
            // If this action is called and the user is already authenticated,
            // it means the user is not a member of the appropriate role for
            // the controller/action requested.
            if (Request.IsAuthenticated)
            {
                RouteValueDictionary values = RouteDataContext.RouteValuesFromUri(uri);
                string controllerName = (string)values["controller"];
                string actionName = (string)values["action"];
                string errorUrl = Url.Action("Error",
                    routeValues: new
                    {
                        message = "You are not authorized to view this content",
                        controllerName,
                        actionName
                    });
                Response.Redirect(errorUrl, true);
            }
            else
            {
                // https://stackoverflow.com/a/21234614
                // Activate the session before login to generate the authentication cookie correctly.
                Session["Workaround"] = 0;
                // Send an OpenID Connect sign-in request.
                string externalLoginCallback = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
                AuthenticationManager.Challenge(new AuthenticationProperties { RedirectUri = externalLoginCallback },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        //public IAuthenticationManager AuthenticationManager
        //{
        //    get { return HttpContext.GetOwinContext().Authentication; }

        //}

        public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {
            ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            ClaimsIdentity claimsIdentity = loginInfo.ExternalIdentity;
            ApplicationUser applicationUser = new ApplicationUser(claimsIdentity);
            IdentityResult result = await UserManager.PersistAsync(applicationUser);
            if (result.Succeeded)
            {
                claimsIdentity = await applicationUser.GenerateUserIdentityAsync(UserManager);
            }
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, claimsIdentity);
            return Redirect(returnUrl);
        }


        [Authorize]
        public void SignOut()
        {
            string callbackUrl = Url.Action("SignOutCallback", "Account", null, Request.Url.Scheme);
            AuthenticationProperties properties = new AuthenticationProperties { RedirectUri = callbackUrl };

            AuthenticationManager.SignOut(
                properties,
                OpenIdConnectAuthenticationDefaults.AuthenticationType,
                CookieAuthenticationDefaults.AuthenticationType,
                Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
        }

        public ActionResult Error(string message, string controllerName = "Account", string actionName = "SignIn")
        {
            Exception exception = new Exception(message);
            HandleErrorInfo handleErrorInfo = new HandleErrorInfo(exception, controllerName, actionName);
            return View("Error", handleErrorInfo);
        }
        public ActionResult SignOutCallback()
        {
            if (Request.IsAuthenticated)
            {
                // Redirect to home page if the user is authenticated.
                return RedirectToAction("Index", "Home");
            }

            return View();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && UserManager != null)
            {
                UserManager.Dispose();
                UserManager = null;
            }
            base.Dispose(disposing);
        }
        #region Helpers
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;
        private IAuthenticationManager _authenticationManager;
        // Used for XSRF protection when adding external logins
        private const string XsrfKey = "XsrfId";
        /// <summary>
        /// Gets a reference to the <see cref="ApplicationSignInManager"/>.
        /// </summary>
        protected ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set { _signInManager = value; }
        }
        protected ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }
        protected IAuthenticationManager AuthenticationManager
        {
            get
            {
                return _authenticationManager ?? HttpContext.GetOwinContext().Authentication;
            }
            private set
            {
                _authenticationManager = value;
            }
        }
        /// <summary>
        /// Ensures the <paramref name="returnUrl"/> belongs to this application.
        /// <para>We don't want to redirect to a foreign page after authentication.</para>
        /// </summary>
        /// <param name="returnUrl">a <see cref="System.String"/> containing the page address that required authorization.</param>
        /// <returns>a <see cref="System.String"/> containing a local page address.</returns>
        private string GetLocalUrl(string returnUrl)
        {
            if (!Url.IsLocalUrl(returnUrl))
            {
                return Url.Action("Index", "Home");
            }
            return returnUrl;
        }
        private class ChallengeResult : HttpUnauthorizedResult
        {
            public ChallengeResult(string provider, string redirectUri)
                : this(provider, redirectUri, null)
            {
            }

            public ChallengeResult(string provider, string redirectUri, string userId)
            {
                LoginProvider = provider;
                RedirectUri = redirectUri;
                UserId = userId;
            }

            public string LoginProvider { get; set; }
            public string RedirectUri { get; set; }
            public string UserId { get; set; }

            public override void ExecuteResult(ControllerContext context)
            {
                var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
                if (UserId != null)
                {
                    properties.Dictionary[XsrfKey] = UserId;
                }
                context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
            }
        }
        private class RouteDataContext : HttpContextBase
        {
            public override HttpRequestBase Request { get; }

            private RouteDataContext(Uri uri)
            {
                string url = uri.GetLeftPart(UriPartial.Path);
                string qs = uri.GetComponents(UriComponents.Query, UriFormat.UriEscaped);

                Request = new HttpRequestWrapper(new HttpRequest(null, url, qs));
            }

            public static RouteValueDictionary RouteValuesFromUri(Uri uri)
            {
                return RouteTable.Routes.GetRouteData(new RouteDataContext(uri)).Values;
            }
        }
        #endregion
    }
}
public void ConfigureAuth(IAppBuilder app)
{
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    // Enable the application to use a cookie to store information for the signed in user
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/LogOn")
    });
    ....
}