【问题标题】:send neatly formatted json data to asp.net web api instead of default [FromBody] behavior将格式整齐的 json 数据发送到 asp.net web api,而不是默认的 [FromBody] 行为
【发布时间】:2017-01-20 07:50:55
【问题描述】:

我正在尝试以一种简洁(更自然)的方式将 Json 格式的数据发送到 Web api 控制器。

让我解释一下。假设我有这个控制器:

[HttpPost]
public class StudentController : ApiController
{

    public void PostSomething([FromBody] string name, [FromBody] Student s) 
    {
        //do something
    }
}

我想发布的 json 数据是这样的(因为它的格式正确):

{
    "name" : "John",
    "student" : {
        "id" : "1",
        "age" : "22"
    }
}

但是我应该将 web api 发送到 parameter bind 的对象应该是这样的:

{
    "John",
    {
        "id" : "1",
        "age" : "22"
    }
}

问题是,如果我使用我想要的 json 格式,name 和 student 对象在控制器的 PostSomething 方法中都将为空。

如何向我的 web api 控制器发送格式类似于第一个示例的 json 请求?

【问题讨论】:

  • 第二个示例对我来说看起来不像是有效的 json,并且在我测试过的每个验证器上都失败了。
  • 就是这样,你是完全正确的。但是如果我以这种方式发送参数,web api 控制器只接受参数。这就是问题
  • 你的问题对我来说并不完全清楚。这是您需要从第 3 方接收的 JSON,还是您需要创建的 JSON 格式才能发送给第 3 方?
  • 第一个例子是我想如何发送 json 请求,web api 控制器不会接受它。第二个例子是web api如何接受json(我不喜欢这样)
  • 然后您需要编写自己的 ParameterBindingAttribute 后代并使用它而不是 [FromBody] 来装饰您的参数。问题是您还必须自己解析这个字符串,因为它不符合任何标准——这将是一个真正的痛苦。您不能让用户发送格式正确的请求吗?

标签: c# asp.net asp.net-web-api asp.net-web-api2


【解决方案1】:

为了使用所需的 JSON 结构,您可以更改 PostSomething 的方法签名并引入一个表示发送数据的类。例如

public class StudentTransferObject {
    public string Name {get; set;}
    public Student Student {get; set;}
}

使用控制器:

[HttpPost]
public class StudentController : ApiController
{    
    public void PostSomething([FromBody] StudentTransferObject studentInformation) 
    {
        //do something
    }
}

【讨论】:

  • 还是不能指定参数名作为key
  • 实际上我错了,您的解决方案完全有效。谢谢
【解决方案2】:
  1. Read text 来自响应正文并自己解析对象:

    [HttpPost] public async Task<string> PostSomething() { string result = await Request.Content.ReadAsStringAsync(); //parse here how you want return result; }

  2. Dynamic serialization 与 custom binding 或 JToken。

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2013-01-24
    • 2017-12-05
    • 1970-01-01
    • 2018-05-23
    • 2016-08-24
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多