LoginSignup
0
0

More than 3 years have passed since last update.

[1] : C#(ASP.NET core)でWeb APIを作ってRequest BodyのXMLを処理してみる

Last updated at Posted at 2020-12-23

概要

.NET coreでWeb APIを作成、Request BodyのXMLを「モデルバインド」でオブジェクトに変換するプログラムを作ってみます

〇 参考資料
 ASP.NET Core でのモデル バインド
 XML シリアル化

[1] Hello Worldやってみよう!

 アプリの初期設定

デバッグ実行(動作確認)

// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    return new string[] { "Hello World!" };
}

[2] XML形式のリクエストボディを受け取れるように設定する

例:以下のXMLを受け取るとき

<BreakfastMenu>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
</BreakfastMenu>

  1. StartUp.cs#ConfigureServices()に以下追記
services.AddMvc().AddXmlSerializerFormatters();
  1. パラメータで受け取るXMLに合わせたクラスを作成

public class BreakfastMenu
{
    public string name { get; set; }
    public string price { get; set; }
    public string description { get; set; }
    public string calories { get; set; }
}
  1. POST APIの引数に上記クラスを設定する
// POST api/values
[HttpPost]
[Consumes("application/xml")]
public ActionResult<IEnumerable<string>> Post([FromBody] BreakfastMenu  value)
  1. デバッグ実行

以下のようにオブジェクト化できていることを確認
1.PNG

[3] 繰り返しのある構造のXMLをバインドする

例:以下のXMLを受け取るとき

<Cat>
    <Plants>
        <Plant>
            <Common>Bloodroot</Common>
            <Botanica>Sanguinaria canadensis</Botanica>
            <Zone>4</Zone>
            <Light>Mostly Shady</Light>
            <Price>$2.44</Price>
            <Availability>031599</Availability>
        </Plant>
        <Plant>
            <Common>Columbine</Common>
            <Botanica>Aquilegia canadensis</Botanica>
            <Zone>3</Zone>
            <Light>Mostly Shady</Light>
            <Price>$9.37</Price>
            <Availability>030699</Availability>
        </Plant>
        <Plant>
            <Common>Marsh Marigold</Common>
            <Botanica>Caltha palustris</Botanica>
            <Zone>4</Zone>
            <Light>Mostly Sunny</Light>
            <Price>$6.81</Price>
            <Availability>051799</Availability>
        </Plant>
    </Plants>
</Cat>
  1. パラメータで受け取るXMLに合わせたクラスを作成

public class Cat
{
    public List<Plant> Plants { get; set; }
}

public class Plant
{
    public string Common { get; set; }
    public string Botanica { get; set; }
    public string Zone { get; set; }
    public string Light { get; set; }
    public string Price { get; set; }
    public string Availability { get; set; }
}
  1. POST APIの引数に上記クラスを設定する
    左記の手順と同じため割愛

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0