响应中应包含Dynamics 365(在线)crm WebAPI Http状态代码(401)

时间:2018-07-08 16:16:22

标签: c# dynamics-crm token http-status-code-401

我正在尝试创建一个已使用Azure AD注册的本机C#应用程序(使用WebAPI)。该应用程序需要在crm中创建特定的实体,但这与我的问题几乎无关。

我尝试使用MSDN提供的示例,尽管它没有引发任何运行时异常,但显示以下消息:

Microsoft.IdentityModel.Clients.ActiveDirectory Error: 4 : 07/06/2018 15:39:31:  - AuthenticationParameters: System.ArgumentException: Unauthorized Http Status Code (401) was expected in the response

Parameter name: response

在用提琴手检查请求/响应时,我注意到所有内容都是通过http发送的,响应是502-错误的网关。把它放在这里以防万一。

我回到MSDN上检查此错误代码的含义,并从此网页获得了以下内容:https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/compose-http-requests-handle-errors

401未经授权请针对以下类型的错误进行预期:

  • BadAuthTicket
  • ExpiredAuthTicket
  • InsufficientAuthTicket
  • InvalidAuthTicket
  • InvalidUserAuth
  • MissingCrmAuthenticationToken
  • MissingCrmAuthenticationTokenOrganizationName
  • RequestIsNotAuthenticated
  • TamperedAuthTicket
  • 未经授权的访问
  • UnManagedInvalidSecurityPrincipal

错误 SEEMS 可能是错误的证明,但由于我现在只是这个领域的初学者,所以我可能是错的。

下面是主.cs文件中的代码

using System;

using Microsoft.Crm.Sdk.Samples.HelperCode;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Test
{
class Program
{

    private HttpClient httpClient;

    static void Main(string[] args)
    {

        Program app = new Program();
        try
        {
            app.ConnectToCRM(args);
        }
        catch (System.Exception ex)
        {
            DisplayException(ex);
        }
        finally
        {
            if (app.httpClient != null)
            { app.httpClient.Dispose(); }
            Console.WriteLine("Press <Enter> to exit the program.");
            Console.ReadLine();
        }
    }


    private void ConnectToCRM(String[] cmdargs)
    {
        Configuration config = null;
        if (cmdargs.Length > 0)
            config = new FileConfiguration(cmdargs[0]);
        else
            config = new FileConfiguration("default");
        Authentication auth = new Authentication(config);
        httpClient = new HttpClient(auth.ClientHandler, true);
        httpClient.BaseAddress = new Uri(config.ServiceUrl + "api/data/v9.0/");
        httpClient.Timeout = new TimeSpan(0, 2, 0);
        httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
        httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    private static void DisplayException(Exception ex)
    {
        Console.WriteLine("The application terminated with an error.");
        Console.WriteLine(ex.Message);
        while (ex.InnerException != null)
        {
            Console.WriteLine("\t* {0}", ex.InnerException.Message);
            ex = ex.InnerException;
        }
    }

}
}

这是用于建立连接的配置文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>

  <connectionStrings>
    <clear />

    <!-- When providing a password, make sure to set the app.config file's security so that only you can read it. -->
    <add name="default" connectionString="Url=https://<tenant>.api.crm11.dynamics.com; Username=user; Password=pass" />
  </connectionStrings>

  <appSettings>
    <!--For information on how to register an app and obtain the ClientId and RedirectUrl
        values see msdn.microsoft.com/.../mt149065 -->

    <!--Active Directory application registration. -->
    <!--These are dummy values and should be replaced with your actual app registration values.-->
    <add key="ClientId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
    <add key="RedirectUrl" value="https://<tenant>.crm11.dynamics.com" />

    <!-- Use an alternate configuration file for connection string and setting values. This optional setting
    enables use of an app.config file shared among multiple applications. If the specified file does
    not exist, this setting is ignored.-->
    <add key="AlternateConfig" value="C:\Temp\crmsample.exe.config" />
  </appSettings>

</configuration>

出于明显的原因,这些字段已被占位符信息填充:)

另一个问题可能是我的直属经理使用Azure AD授权了该应用程序,因为他具有完全控制权,而我正尝试使用我的凭据来授权该应用程序,但是我几乎100%肯定这不是更改用户名的情况和密码字段对我遇到的错误没有影响。

能否让我知道我想念的是什么?我怀疑这很简单,但是最近两天我一直在阅读MSDN文档,似乎无法解决我的问题?

0 个答案:

没有答案