C# Microsoft.Graph.ServiceException:代码:methodNotAllowed

C# Microsoft.Graph.ServiceException:代码:methodNotAllowed,c#,.net-core,microsoft-graph-api,azure-ad-b2c,C#,.net Core,Microsoft Graph Api,Azure Ad B2c,在将以下请求发送给我的b2c租户后,我得到了400英镑。有关详细信息,请参见下文: Microsoft.Graph.ServiceException:代码:methodNotAllowed 消息:此URL不支持该方法 我需要重置用户密码,因此我将按照此处所述进行操作: 这是我的密码: public async Task<string> ResetPassword(string userId) { var newPassword = Helper

在将以下请求发送给我的b2c租户后,我得到了400英镑。有关详细信息,请参见下文:

Microsoft.Graph.ServiceException:代码:methodNotAllowed 消息:此URL不支持该方法

我需要重置用户密码,因此我将按照此处所述进行操作:

这是我的密码:

public async Task<string> ResetPassword(string userId)
        {
            var newPassword = Helpers.PasswordHelper.GenerateNewPassword(4, 8, 4);
            var result = await graphClient
                .Users[userId]
                .Authentication.PasswordMethods["{passwordAuthenticationMethod-id}"]
                .ResetPassword(newPassword, null)
                .Request()
                .PostAsync();
            return result.NewPassword;
        }
公共异步任务重置密码(字符串userId)
{
var newPassword=Helpers.PasswordHelper.GenerateNewPassword(4,8,4);
var结果=等待图形客户端
.Users[userId]
.Authentication.PasswordMethods[“{passwordAuthenticationMethod id}”]
.ResetPassword(新密码,null)
.Request()
.PostAsync();
返回result.NewPassword;
}
我添加到项目中的包

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Graph.Auth" Version="1.0.0-preview.4" />
    <PackageReference Include="Microsoft.Graph.Beta" Version="0.39.0-preview" />
    <PackageReference Include="Microsoft.Identity.Client" Version="4.13.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.2" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
  </ItemGroup>
</Project>

netcoreapp3.1

我做错了什么?

不建议使用Microsoft Graph Beta版:

如果要更改用户密码,可以尝试使用Microsoft Graph API,只需尝试下面的简单控制台应用程序即可:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    
    namespace graphsdktest
    {
        class Program
        {
    
            public static async Task<string> GetAccessToken()
            {
    
                using (var client = new HttpClient())
                {
                    var clientId = "<app id>";
                    var clientSecret = "<app secret>";
                    var tenantID = "<tenant id>";
                    var adminUserName = "<b2c admin user account>";
                    var password = "<b2c admin user password>";
    
                    var tokenUrl = @"https://login.microsoftonline.com/" + tenantID + "/oauth2/v2.0/token";
                    client.BaseAddress = new Uri(tokenUrl);
                    
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    
                    List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
                    postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
                    postData.Add(new KeyValuePair<string, string>("client_id", clientId));
                    postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    postData.Add(new KeyValuePair<string, string>("scope", "openid"));
                    postData.Add(new KeyValuePair<string, string>("username", adminUserName));
                    postData.Add(new KeyValuePair<string, string>("password", password));
    
                    FormUrlEncodedContent requestBody = new FormUrlEncodedContent(postData);
                  
                    var request = await client.PostAsync(tokenUrl, requestBody).ConfigureAwait(false);
                    var response = await request.Content.ReadAsStringAsync();
                    var responseData = JsonConvert.DeserializeObject(response);
                  
                    return ((dynamic)responseData).access_token;
                }
            }
            static void Main(string[] args)
            {
                var accessToken = GetAccessToken().GetAwaiter().GetResult();
    
                var userID = "<target user id>";
                var newPass = "<new password>";
    
                var requstURL = @"https://graph.microsoft.com/v1.0/users/" + userID;
    
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(requstURL);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                httpWebRequest.Method = "PATCH";
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                string json = "{\"passwordProfile\":{\"forceChangePasswordNextSignIn\":false,\"password\":\"" + newPass + "\"}}";
    
                    streamWriter.Write(json);
                }
    
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    
                //if code is 204 means request has been accepted, change password successfully
                Console.WriteLine((int)httpResponse.StatusCode);
            }
    }

}
使用Newtonsoft.Json;
使用制度;
使用System.Collections.Generic;
使用System.IO;
Net系统;
使用System.Net.Http;
使用System.Net.Http.Header;
使用System.Threading.Tasks;
名称空间图测试
{
班级计划
{
公共静态异步任务GetAccessToken()
{
使用(var client=new HttpClient())
{
var clientId=”


有关此API的更多信息,请参阅。

我通过将角色
用户管理员
分配给我的b2c应用程序,并生成一个密码,以便您可以使用它来配置您的C应用程序,从而使使用SDK的Graph API调用正常工作

{
  "appSettings": {

    // MAKE SURE THESE REPRESENT YOUR TENANT SETTINGS
    "TenantId": "XXXXX.onmicrosoft.com",
    "AppId": "2a4c5942-7156-4fce-b524-XXXXXXXXX",
    "ClientSecret": "7746Dj-_h4rrK-XXXXXXXXXX",
  }
}
更新密码的代码为:

public async Task<string> UpdateUserPassword(string userId)
{
    var password = Helpers.PasswordHelper.GenerateNewPassword(4, 8, 4);
    var user = new User
    {
        Id = userId,
        PasswordProfile = new PasswordProfile
        {
            Password = password,
            ForceChangePasswordNextSignIn = false
        },
        PasswordPolicies = "DisablePasswordExpiration"

    };

    await graphClient
        .Users[userId]
        .Request()
        .UpdateAsync(user);

    return password;
}

public异步任务UpdateUserPassword(字符串userId)
{
var password=Helpers.PasswordHelper.GenerateNewPassword(4,8,4);
var user=新用户
{
Id=用户Id,
PasswordProfile=新的PasswordProfile
{
密码=密码,
ForceChangePasswordNextSignIn=false
},
PasswordPolicys=“DisablePasswordExpiration”
};
等待graphClient
.Users[userId]
.Request()
.UpdateAsync(用户);
返回密码;
}

但是,我已经设置了
ForceChangePasswordNextSignIn=false
b2c在首次使用密码登录后不会要求用户更改密码。如果您将其设置为
true
我无法登录。我正在使用自定义策略进行登录/注册。有什么想法吗?

不允许使用的方法405:PIs用户id是正确的用户id,不是奇怪的东西?我想对您所经历的情况的一种解释是,api将所有内容转换为端点URI,将用户id替换为路径,最终匹配了不接受post的内容。但这只是一个想法。您的帐户中是否有“全局管理员”或“身份验证管理员”或“特权身份验证管理员”角色您正在使用哪个nt登录?进展如何?您的问题解决了吗?用户能否在使用新密码登录后更改密码?如果您希望用户在登录后设置新密码,您可以在json中将forceChangePasswordNextSignIn的值设为True。非常感谢。这是我所知道的,但不确定在哪里可以找到t他有正确的信息来测试你发布的代码,所以你能确认这是否正确吗?我将尝试添加一个图像。顺便说一句,我看不到你发布的权限。