无法调用任何验证webapi的方法,甚至可以登录或注册

时间:2017-05-30 05:51:40

标签: c# authentication asp.net-web-api

我已经使用身份验证创建了Web API,但是当我尝试使用控制台应用程序注册它时,我收到以下错误:

  

response = {StatusCode:401,ReasonPhrase:' Unauthorized',版本:   1.1,内容:System.Net.Http.StreamContent,Headers:{X-SourceFiles:   =?UTF-8 2 B 4 RDpcU1RFQ0hfUHJvamVjdFxQcm9qZWN0c1xMb3lhbHR5XFNhbnN1dGVjaC5MdHkuRGF0YS5XZWIuQXBpXGFwaVxBY2NvdW50XFJlZ2lzdGVy?=   缓存控制:私有服务器:Microsoft-IIS / 8.0 WWW-Authenticate:   持票人,谈判,NTLM X-Powered-By:ASP.NET

如何使用控制台客户端注册到api?

我可以从postman调用注册方法并注册到应用程序

这是我注册的控制台代码

static async Task<string> PostRequest4(string token, string apiBaseUri, string requestPath, RegisterBindingModel t)
    {
        HttpClientHandler hndlr = new HttpClientHandler(); 
        hndlr.UseDefaultCredentials = true;
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri("http://localhost:38811/");
            client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //make request
            HttpResponseMessage response = await client.PostAsJsonAsync(requestPath, t);
            //make request

            Stream stream = await response.Content.ReadAsStreamAsync();
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(ResponseMessage));
            ResponseMessage objResponse = (ResponseMessage)dataContractJsonSerializer.ReadObject(stream);
            string res = "";
            if (objResponse == null)
            {
                res = "error occurred!";
            }
            else
            {
                if (objResponse.ErrorMessage != null)
                {
                    res = "error occurred!";
                }
                else if (objResponse.IsSuccess)
                {
                    res = "Item ID " + objResponse.ID.ToString() + " have been added Successfully!";
                }

            }
            return res;
        }
    }

在传递之前,如果我添加以下行,那么我可以成功注册到应用程序

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

这里我使用现有用户&#34;用户名和密码&#34;

通过以下方法获得令牌
private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
    {
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //setup login data
            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"), 
                new KeyValuePair<string, string>("username", userName), 
                new KeyValuePair<string, string>("password", password), 
            });

            //send request
            HttpResponseMessage responseMessage = await client.PostAsync(Token , formContent);
            //get access token from response body
            var responseJson = await responseMessage.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseJson);
            return jObject.GetValue("access_token").ToString();
        }
    }

我想调用register方法而不涉及现有用户(用户名和密码)

如果有人可以帮助我,我将非常感激 〜感谢〜

1 个答案:

答案 0 :(得分:0)

从项目属性设置匿名身份验证启用解决了我的问题。谢谢