Web API サーバーに接続するための WPF アプリケーションを作成したいと考えています。しかし、私はWPFの初心者です。さらに悪いことに、.net でも。
実際、私はすでにうまくいっています。このhttp://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-applicationに従ってください。
さらに検索した結果、私は完全に間違った方法 (winform の方法) で作業していることがわかりました。そして、ほとんどのコミュニティが言ったように、MVVM スタイルを使用する必要があるようです。そこで、すべてのコードを書き直すことにしました。
プリズムを使用してモジュールを作成し、名前とパスワードを ViewModel クラスにバインドします。これで、Textbox から名前とパスワードを取得できます。
まず、使用するすべての ViewModel の httpclient インスタンスを作成できませんでした。以下は問題のリンクです
すでに構築されたインスタンスをユニティに登録するのは難しいですか?
だから私はこのように書くことを決心します。最初にインターフェイスを作成します。
public interface IData
{
IEnumerable<device> getDevicesByUser(user user);
IEnumerable<user> getUsers();
currentUser getCurrentUserInfo();
}
実装インターフェース
public class HttpService : IData
{
HttpClient client = new HttpClient();
public HttpService()
{
client.BaseAddress = new Uri("https://localhost:3721");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public IEnumerable<device> getDevicesByUser(user user)
{
throw new NotImplementedException();
}
public IEnumerable<user> getUsers()
{
throw new NotImplementedException();
}
public currentUser getCurrentUserInfo()
{
throw new NotImplementedException();
}
}
その後、Unity にインスタンスを登録し、すべての ViewModel で使用できるようになりました。私は2つの方法を使用していますが、どちらも機能しません。正しい方法についてアドバイスが必要です。
最初の方法。インターフェイス メソッドごとに非同期メソッドを記述します。
public currentUser getCurrentUserInfo()
{
return getCurrentUserInfoFromServer();
}
private async void getCurrentUserInfoFromServer()
{
try
{
var response = await client.GetAsync("api/user");
response.EnsureSuccessStatusCode();
var currentuser = await response.Content.ReadAsAsync<currentUser>();
}
catch (Newtonsoft.Json.JsonException jEx)
{
MessageBox.Show(jEx.Message);
}
catch (HttpRequestException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
しかし、async は void と task 以外の型を返すことができないようです。そして、それは奇妙に思えます。そのため、すべてのリクエストを 1 つのメソッドに書き込もうとしています。
private async void getData(string requestUri)
{
try
{
var response = await client.GetAsync("api/user"+requestUri);
response.EnsureSuccessStatusCode();
var ? = await response.Content.ReadAsAsync<?>();
}
catch (Newtonsoft.Json.JsonException jEx)
{
MessageBox.Show(jEx.Message);
}
catch (HttpRequestException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
このコードには、最初のコードと同じ問題がまだあります。void と task 以外の型を返すことはできません。また、データを動的に取得する方法も問題ですか?