DEV Community

tackme
tackme

Posted on

3 3

コントローラでDictionary型のGETパラメータを受け取る

コントローラのアクションでDictionary型のGETパラメータを受け取るには、以下のようなフォーマットでパラメータを記述します。

https://example.com/api/Sample/SampleData?param[key1]=val1&param[key2]=val2&...
Enter fullscreen mode Exit fullscreen mode

上記のリクエストを投げると、アクションで定義したparam引数で以下のように値を受け取ることができます。

[Route("api/[controller]")]
public class SampleController : Controller
{
    [HttpGet("[action]")]
    public Data SampleData(Dictionary<string, string> param)
    {
        var val1 = param["key1"];
        var val2 = param["key2"];
        return ...;
    }
}
Enter fullscreen mode Exit fullscreen mode

注意点

先ほどの例でparamパラメータ無しのリクエストを投げるとアクションが見つからずエラーが発生します。

https://example.com/api/Sample/SampleData
=> 500 Error
Enter fullscreen mode Exit fullscreen mode

空のディクショナリを渡すには、以下のような値無しのparamパラメータ付きのリクエストを投げる必要があります。

https://example.com/api/Sample/SampleData?param
Enter fullscreen mode Exit fullscreen mode
[HttpGet("[action]")]
public InitData Init(Dictionary<string, string> param)
{
    var _ = param.Count; // => 0
    return ...;
}
Enter fullscreen mode Exit fullscreen mode

参考

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay