C#教科書を身につける.体験ネットワークプログラミング
7903 ワード
https://www.youtube.com/watch?v=u3DP9ms3bxk&list=PLO56HZSjrPTB4NxAsEP8HRk6YKBDLbp7m&index=83
グローバルネットワークプログラミング ローカルネットワークではなくサーバにデータを送信する
2.プロジェクト
TodoApp.Apis
Talend APIテスト(Postmanok) を使用
3.異性体(他の場所でも使用可能)
他陣営(装置)からの へのアクセスを許可する.
TodoApp.Apis.Tests.ConsoleApp
WebAPIを実行
コンソールの実行
1.ネットワークプログラミング
2.プロジェクト
01.47までのプロジェクトソリューションでAPIソリューションフォルダを作成し、WebアプリケーションAPIプロジェクトを作成



02.モデルを参照

03.ContreolersフォルダでTodosControllerを使用します。cs作成

04.GETサンプルコード(TodosController.cs)
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TodoApp.Apis.Controllers
{
[Route("api/[Controller]")]
public class TodosController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
return Content("안녕하세요.");
}
}
}

05.POSTサンプルコード(TodosController.cs)
using CShopTodoApp.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TodoApp.Apis.Controllers
{
[Route("api/[Controller]")]
public class TodosController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
return Content("안녕하세요.");
}
[HttpPost]
public IActionResult Add([FromBody]Todo dto)
{
return Ok(dto);
}
}
}


06.実施モデルレポート
using CShopTodoApp.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TodoApp.Apis.Controllers
{
[Route("api/[Controller]")]
public class TodosController : ControllerBase
{
private readonly ITodoRepository _repository;
public TodosController()
{
_repository = new TodoRepositoryJson(@"C:\Temp\Todos.json");
}
[HttpGet]
public IActionResult GetAll()
{
return Ok(_repository.GetAll());
}
[HttpPost]
public IActionResult Add([FromBody]Todo dto)
{
_repository.Add(dto);
return Ok(dto);
}
}
}




3.異性体(他の場所でも使用可能)
01. TodoApp.Apis / Startup.csの変更
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TodoApp.Apis
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options => { // 다른 진영에서의 접근 허용
options.AddDefaultPolicy(build =>
{
build.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCors(); // 다른 진영에서의 접근 허용
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}



02.コンソールでテスト(APIでコンソールプロジェクトを作成)



03. Newtonsoft.json(NuGet)を参照


04.コンソール計画。csの作成(Gitの保存)
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace TodoApp.Apis.Tests.ConsoleApp
{
class Program
{
static async Task Main(string[] args)
{
string url = "https://localhost:5001/api/Todos";
using (var client = new HttpClient())
{
// 데이터 전송
var json = JsonConvert.SerializeObject(new Todo { Title = "HttpClient", IsDone = true});
var post = new StringContent(json, Encoding.UTF8, "application/json");
await client.PostAsync(url, post);
// 데이터 수신
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var todos = JsonConvert.DeserializeObject<List<Todo>>(result);
foreach (var item in todos)
{
Console.WriteLine($"{item.Id} - {item.Title}({item.IsDone})");
}
}
}
}
public class Todo
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsDone { get; set; }
}
}
まず


Reference
この問題について(C#教科書を身につける.体験ネットワークプログラミング), 我々は、より多くの情報をここで見つけました https://velog.io/@ansalstmd/C교과서-마스터하기-48.-네트워크-프로그래밍-맛보기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol