【问题标题】:System.Threading.ThreadStateException in ASP.NET MVC 5 when Acquire Token from WAAD从 WAAD 获取令牌时,ASP.NET MVC 5 中的 System.Threading.ThreadStateException
【发布时间】:2014-04-29 00:13:14
【问题描述】:

我正在实现以下场景:ASP.NET MVC 5 应用程序使用 Azure Active Directory 身份验证访问 OData WebAPI(如本文中:http://msdn.microsoft.com/en-us/magazine/dn463788.aspx)。

但是,当我调用 AuthenticationContext.AcquireToken 时,我得到 System.Threading.ThreadStateException 说:ActiveX 控件 '8856f961-340a-11d0-a96b-00c04fd705a2' 无法实例化,因为当前线程不在单线程中 公寓。

已编辑:

重现步骤:

  1. 使用组织身份验证创建新的 MVC 项目。使用您的 Windows Azure 域和 MSDN 帐户

  2. 通过 NuGet 添加 Actice 目录身份验证库

  3. 使用以下代码添加操作:

    public async Task<ActionResult> Index(){        
    
    
            AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/domain.onmicrosoft.com");
            AuthenticationResult ar = ac.AcquireToken("https://domain.onmicrosoft.com/WindowsAzureADWebAPITest",
                                                        "a4836f83-0f69-48ed-aa2b-88d0aed69652",
                                                        new Uri("https://domain.onmicrosoft.com/myWebAPItestclient")
                                                    );
            // Call Web API
            string authHeader = ar.CreateAuthorizationHeader();
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://server.com:44353/api/Values");
            request.Headers.TryAddWithoutValidation("Authorization", authHeader);
            HttpResponseMessage response = await client.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();
    
            return View();
        }
    
  4. 运行代码并重现问题(AcqureToken 方法调用)。

请提出修复建议。

谢谢!

【问题讨论】:

  • "like in this article",如果文章没有重现问题,请简化发布代码。

标签: asp.net-mvc multithreading azure active-directory sta


【解决方案1】:

AcquireToken() 的特定重载只能在本机客户端应用程序中使用,因为它处理用户身份验证的方式是打开浏览器窗口到 login.windows.net。这要求应用托管浏览器 ActiveX 控件,这就是它需要 STA 线程的原因。

现在,在您的示例中,代码在无法托管 ActiveX 控件的服务器机器上的 IIS 内运行。

您真正需要的是这里描述的委托:http://www.cloudidentity.com/blog/2013/10/29/using-adals-acquiretokenby-authorizationcode-to-call-a-web-api-from-a-web-app/

同一作者,只是文章不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多