C#を使用して他のアプリケーションからAsp.Net WebAPIエンドポイントを使用するにはどうすればよいですか?
HttpClient classは、URLからHTTP要求/応答を送受信するための基本クラスを提供します。これは、.NETFrameworkでサポートされている非同期機能です。 HttpClientは、複数の同時リクエストを処理できます。これは、HttpWebRequestとHttpWebResponseの上のレイヤーです。 HttpClientを使用するすべてのメソッドは非同期です。 HttpClientはSystem.Net.Http名前空間で利用できます。
StudentControllerとそれぞれのアクションメソッドを持つWebAPIアプリケーションを作成しましょう。
学生モデル
namespace DemoWebApplication.Models{
public class Student{
public int Id { get; set; }
public string Name { get; set; }
}
} 学生コントローラー
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class StudentController : ApiController{
List<Student> students = new List<Student>{
new Student{
Id = 1,
Name = "Mark"
},
new Student{
Id = 2,
Name = "John"
}
};
public IEnumerable<Student> Get(){
return students;
}
public Student Get(int id){
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}
それでは、コンソールアプリケーションを作成しましょう。 上記で作成したWebApiエンドポイントを使用して、学生の詳細を取得したい場合。
例
using System;
using System.Net.Http;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
using (var httpClient = new HttpClient()){
Console.WriteLine("Calling WebApi for get all students");
var students = GetResponse("student");
Console.WriteLine($"All Students: {students}");
Console.WriteLine("Calling WebApi for student id 2");
var studentForId = GetResponse("student/2");
Console.WriteLine($"Student for Id 2: {students}");
Console.ReadLine();
}
}
private static string GetResponse(string url){
using (var httpClient = new HttpClient()){
httpClient.BaseAddress = new Uri("https://localhost:58174/api/");
var responseTask = httpClient.GetAsync(url);
var result = responseTask.Result;
var readTask = result.Content.ReadAsStringAsync();
return readTask.Result;
}
}
}
} 出力
Calling WebApi for get all students
All Students: [{"Id":1,"Name":"Mark"},{"Id":2,"Name":"John"}]
Calling WebApi for student id 2
Student for Id 2: {"Id":2,"Name":"John"} 上記の例では、WebApiのエンドポイントが別のコンソールアプリケーションから呼び出されていることがわかります。
-
C#ASP.NET WebAPIでCORSの問題を解決するにはどうすればよいですか?
クロスオリジンリソースシェアリング (CORS)は、追加のHTTPヘッダーを使用して、あるオリジンで実行されているWebアプリケーションに、別のオリジンから選択されたリソースへのアクセスを許可するようにブラウザーに指示するメカニズムです。 Webアプリケーションは、自身とは異なるオリジン(ドメイン、プロトコル、またはポート)を持つリソースを要求すると、クロスオリジンHTTPリクエストを実行します。 たとえば、フロントエンド(UI)とバックエンド(サービス)を持つアプリケーションについて考えてみましょう。フロントエンドがhttps://demodomain-ui.comから提供されているとしま
-
C#ASP.NET WebAPIのアクションメソッドからカスタム結果タイプを返す方法は?
IHttpActionResultインターフェイスを実装することで、結果タイプとして独自のカスタムクラスを作成できます。 。 IHttpActionResultには、HttpResponseMessageインスタンスを非同期的に作成する単一のメソッドExecuteAsyncが含まれています。 public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken); } コントロ