如何将用户名密码从Windows应用程序传递到Web API?

时间:2017-02-21 14:11:55

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

我想从Windows应用程序调用web api。

2 个答案:

答案 0 :(得分:3)

您可以使用WebRequest来调用WebApi。这些线上的东西。很难理解你到底想要什么。在提问时,请尽量详细说明您已尝试过的内容以及失败的内容。这不是编码服务。

WebRequest request = WebRequest.Create("http://webapiaddress");
request.Credentials = new System.Net.NetworkCredential("username", "password");

更多信息后编辑:

你可以在这些方面使用一些东西:

    public async Task<TResult> GetAsync<TResult>(string uriString) where TResult : class
    {
        var uri = new Uri(uriString);
        using (var client = GetHttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(uri);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                //Log.Error(response.ReasonPhrase);
                return default(TResult);
            }
            var json = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResult>(json, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
        }
    }

    private HttpClient GetHttpClient()
    {
        var client = new HttpClient();
        var username = // get your username
        var password = // get your password
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }

答案 1 :(得分:0)

 var client = new HttpClient();
 var stringContent = new StringContent(JsonConvert.SerializeObject(objuser), Encoding.UTF8, "application/x-www-form-urlencoded");

 stringContent.Headers.Add("j_username", objuser.j_username);
 stringContent.Headers.Add("j_password", objuser.j_password); 
 HttpResponseMessage response = client.PostAsync(@"URL"?j_username=" + objuser.j_username + "&j_password=" + HttpUtility.UrlEncode(objuser.j_password), stringContent).Result;
 string path2 = "URL/getall";

 var response1 = await client.GetAsync(path2);

  var data = await response1.Content.ReadAsStringAsync();
     if (true)
        {
     var data2 = JsonConvert.DeserializeObject<RootObject>(data);
         }