通过Azure API管理Rest服务创建用户

时间:2016-03-30 19:40:26

标签: c# api rest azure

我是Azure API管理Rest Service的新手。我创建了一个新的API管理,其中包含sharedaccesstoken

using (HttpClient httpClient = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
    request.Headers.Authorization =
    new AuthenticationHeaderValue("SharedAccessSignature", sharedAccessSignature);
    request.Content = new StringContent("{\"accountEnabled\": true,\"creationType\": \"LocalAccount\",\"displayName\": \"Alex Wu\",\"passwordProfile\": {\"password\": \"Test1234\",\"forceChangePasswordNextLogin\": false},\"signInNames\": [{\"type\": \"userName\",\"value\": \"AlexW\"},{\"type\": \"emailAddress\",\"value\": \"AlexW@example.com\"}]}");
    HttpResponseMessage response = await httpClient.SendAsync(request);
    response.EnsureSuccessStatusCode();
    responseBody = await response.Content.ReadAsStringAsync();
}

当我执行上面的代码时,我收到一个错误:

{StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{  Date: Wed, 30 Mar 2016 19:38:15 GMT  Content-Length: 73  Allow: GET  Content-Type: application/json; charset=utf-8}}

有人可以帮助我继续前进,这样我就能通过REST服务创建新用户。

2 个答案:

答案 0 :(得分:0)

我刚刚阅读了https://docs.microsoft.com/en-us/rest/api/apimanagement/user/createorupdate中指定的API参考。

对于初学者,你应该使用HttpMethod.Put而不是Post。请求路径应为base url + / users / {unique uid}。此外,据我所知,您尝试传递的属性不适用于此事务。

如果您正在尝试完成其他内容,然后创建Azure API管理用户实体,请提供建议,我将尝试为您提供更多指导。

答案 1 :(得分:0)

你的回答确实帮助了我。下面的实现让我完成了我的任务。

  string requestUrl = string.Format("{0}/users/{1}?api-version={2}", baseUrl, userGuid, apiVersion);
            string responseBody = null;
            try
            {
                using (HttpClient httpClient = new HttpClient())
                { 
 var request = new HttpRequestMessage(HttpMethod.Put, requestUrl);
                        request.Headers.Authorization =
                            new AuthenticationHeaderValue("SharedAccessSignature", sharedAccessSignature);
                        request.Content = new StringContent("{\"firstName\": \"MyFirstName\",\"lastName\": \"MyLastName\",\"email\": \"example@mail\",\"password\": \"Password;\",\"state\": \"active\"}", Encoding.UTF8,"application/json");
                        HttpResponseMessage response = await httpClient.SendAsync(request);`enter code here`
                        response.EnsureSuccessStatusCode();
                        responseBody = await response.Content.ReadAsStringAsync();
}
            }