首页 > 解决方案 > 有什么方法可以检测 Nancy 请求正文中是否存在可为空的参数

问题描述

背景

我有一个使用 Nancy 1.4.3 的网络服务器。Nancy 模型绑定用于反序列化来自带有 json 主体的 HTTP 请求的数据。请参见下面的示例。

例子

服务器中的端点:

private class ARequestBody
{
    public int? Parameter1 { get; set; }
    public int? Parameter2 { get; set; }
}

[Post("examplerequest")]
public Response AMethod()
{
    var body = this.Bind<ARequestBody>

    //Do stuff with data in body
    var foo = body.Parameter1;
    var bar = body.Parameter2;

    return new Response();
}

对端点的请求:

Method: POST
Path: [server_address_etc]/examplerequest
Body:
{
    "Parameter1" : 123,
    "Parameter2" : null
}

如果向此端点发出请求,例如请求正文中的 Parameter1 为 null,则 body.Parameter1 在绑定后将具有 null 值,这是可以理解的。但是,如果请求中不包含 Parameter1,则 body.Parameter1 也将为 null。

问题

有什么方法可以检测请求正文中是否包含参数?如果可能的话,我希望能够区分:

  1. 包含在请求正文中但值为 null 的可为空参数
  2. 如果参数根本不包含在请求正文中。

标签: nancy

解决方案


推荐阅读