【问题标题】:Single Web API request which accepts all type of inputs in C#接受 C# 中所有类型的输入的单个 Web API 请求
【发布时间】:2021-01-01 04:06:06
【问题描述】:

我设计了一个请求,它将接受所有类型的输入,如 XML、JSON 等。
因此,该方法将响应并给出相应的输出。
有没有这方面的例子?

我已经尝试了下面的代码。
当我从邮递员那里调用它时,它给出了一个

415 错误

[HttpPost("/GetOutput", Name = nameof(GetOutput))]
[Consumes("application/xml","application/json", "text/plain")]        
public IActionResult GetOutput(dynamic request)
{
    //process         
    return new ObjectResult(res.ToString());
}

【问题讨论】:

  • [FromBody]dynamic的目的是什么?
  • 415 是不受支持的媒体类型。你在发什么?

标签: c# http post asp.net-core-webapi


【解决方案1】:

允许用户提交所有类型的输入可能是一个超级危险的想法。你永远不知道你的用户会提交什么。

如果您只想接受基于文本的输入,例如您的示例尝试做的事情,接受json/xml/text,您可以试试这个:

1.定义绑定模型。没有dynamic

public class MyRequestBindingModel
{
    // the type of Content.
    public string Type { get; set; }

    // the serialized json/xml/text content.
    public string Content { get; set; }
}

2。您的控制器操作:

[HttpPost("/GetOutput")]
public IActionResult GetOutput([FromBody] MyRequestBindingModel request)
{
    // process
    switch(request.Type.ToLower())
    {
        case "json": _processJsonInput(request.Content); 
        case "xml": _processXmlInput(request.Content); 
        default: _processTextInput(request.Content); 
    }

    // do something else you want
}

上例中的switch 语句只是展示了如何根据提供的Type 处理字符串内容。

如果您想在 API 调用中的 Content 是 XML 时返回 XML,这个答案可能会有所帮助:
Helpful Answer

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2018-02-26
    • 2020-10-14
    • 2014-08-28
    • 1970-01-01
    相关资源
    最近更新 更多