セルフサーバーセルフホスト

System.Web.Http.SelfHost名前空間クラスを使用して「独自のサーバーに」書き込みます。

このネームスペースのクラスの使用に直面したとき、以下からアクセス可能なWebマズルを作成する必要が生じました。

画像 Windowsサービス。

2つのプロジェクトを作成しましょう
1-実際にサーバー
2番目にはAPIコントローラが含まれます

サーバーは次のようになります。

public class HTTPServer { public static string ServiceAddress = string.Format("http://{0}:{1}", Common.Config.HTTPServerIP /*  IP*/, Common.Config.HTTPServerPort /*   */); private HttpSelfHostServer _HTTPserver = null; private static HttpSelfHostConfiguration _config = null; private static HttpSelfHostServer CreateHost() { _config = new HttpSelfHostConfiguration(ServiceAddress); AssembliesResolver assemblyResolver = new AssembliesResolver(); _config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver); _config.Routes.MapHttpRoute( name: "default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { controller = "Home", id = RouteParameter.Optional }); HttpSelfHostServer server = new HttpSelfHostServer(_config); server.OpenAsync().Wait(); return server; } public void Start() { _HTTPserver = CreateHost(); } public void Stop() { if (_HTTPserver != null) _HTTPserver.CloseAsync().Wait(); } } 


ここで、サービスはAPIコントローラーの取得元を指定する必要があります。これは、サーバープロジェクトのクラスを継承するためです。

 DefaultAssembliesResolver 


 class AssembliesResolver : DefaultAssembliesResolver { public override ICollection<Assembly> GetAssemblies() { ICollection<Assembly> baseAssemblies = base.GetAssemblies(); List<Assembly> assemblies = new List<Assembly>(baseAssemblies); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Infrastructure.Server.HTTP.Controllers.dll" /*,      api  */); assemblies.Add(Assembly.LoadFrom(path)); return assemblies; } } 


コントローラーを含む2番目のプロジェクトに渡します。 ここに、コントローラの末尾を含む名前のクラスを追加します。たとえば、次のとおりです。

ユーザーコントローラー
地域コントローラー
デバイスコントローラー

System.Web.Http名前空間のApiControllerクラスをオーバーロードし、いくつかのメソッドを追加します。

 public class UsersController : ApiController { [HttpGet] public object hello() { return "Hello page"; } [HttpPost] public object SendData(int data) { return new HttpResponseMessage(HttpStatusCode.OK); } } 


もう一度行に注目しましょう。

 "api/{controller}/{action}/{id}" 


この行は、ルートパターンについて説明しています。
ServiceAddressで指定されたIPアドレスとポートにリクエストを送信し、次に/ api 、次に/ コントローラープレフィックスなしのコントローラー クラスの名前を書き込みます。次に例を示します。

ユーザー
地域
装置
、-そして/メソッド名とパラメーターリストを介して&

アプリケーションをデバッグするには、 Postman Chrome拡張機能-REST Client 0.8.4.10を使用します。

getリクエストの例を次に示します。
192.168.1.1:8080 / api / Users / Hello

Postリクエストの例を次に示します。
192.168.1.1:8080 / api / Users / SendData?データ= 1

Source: https://habr.com/ru/post/J242917/


All Articles