初めまして、アキちゃんです。
備忘録をかねてブログを書くことにしました。
今回はにControllerでGet・Post実装ついて書きます。
それでは早速・・・ControllerでGet・Post実装!
Lesson.1 事の発端
なのでBlazorでApiの実装を試してみようと思います。
Lesson.2 Program.cs
BlazorではControllerでApiを実装する際、Program.csに追加の設定をしなければなりません。
app.UseEndpoints(userEndPpoints=>
{
userEndPpoints.MapControllers();
});
Lesson.3 Controller - Get
Getの実装ではあんまり考えることはありません。
ざっくりこうです。
[Route("api/get")]
public class GetController : Controller
{
private readonly IWebHostEnvironment environment;
public GetController(IWebHostEnvironment environment)
{
this.environment = environment;
}
[HttpGet("string")]
public IActionResult GetString()
{
try
{
return Content("Hello World");
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
public class JsonSample
{
[JsonPropertyName("number")]
public int Number { get; set; }
[JsonPropertyName("content")]
public string? Content { get; set; }
}
[HttpGet("json/{content}")]
public IActionResult GetJson(string content)
{
try
{
return Content(JsonSerializer.Serialize(new JsonSample { Number = 1, Content = content }), "application/json", System.Text.Encoding.UTF8);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
[HttpGet("xlsx/{filePath}")]
public IActionResult GetXlsxFile(string filePath)
{
try
{
var rslt = System.IO.File.ReadAllBytes(filePath);
return File(rslt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(filePath));
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
}
Lesson.4 Controller - Post
Postで行うことでいちばんミソとなるのはFileのアップロードだと思います。
あと、稀に送られてきたJsonを書き込まずStreamでそのまま使いたい時だと思います。
ざっくりこうです。
[Route("api/post")]
public class PostController : Controller
{
private readonly IWebHostEnvironment environment;
public PostController(IWebHostEnvironment environment)
{
this.environment = environment;
}
[HttpPost("file")]
public IActionResult SetFile(IFormFile file)
{
try
{
using (var stream = new FileStream(Path.Combine(environment.WebRootPath, file.Name), FileMode.Create))
{
file.CopyTo(stream);
}
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
public class JsonSample
{
[JsonPropertyName("number")]
public int Number { get; set; }
[JsonPropertyName("content")]
public string? Content { get; set; }
}
[HttpGet("json")]
public async Task<IActionResult> SetJson(IFormFile file)
{
try
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] buffer = memoryStream.ToArray();
// getのなかに取得したJsonが入る
// 新規で書き込んで作るもよし・既存のファイルをいじるもよし
var get = JsonSerializer.Deserialize<JsonSample>(Encoding.ASCII.GetString(buffer));
}
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
}
Lesson.5 あとがき
*20221219追記
using System.Text.Json.Serialization;でJsonを操作する際は元となるクラスの変数をプロパティにしないとSerialize、Deserializeがうまく動かずJsonが生成されません。
以上!