【问题标题】:Can you post an anonymous object as json to a webapi method and it match the properties of the json object to the parameters of the webapi call?您可以将匿名对象作为 json 发布到 webapi 方法,并将 json 对象的属性与 webapi 调用的参数匹配吗?
【发布时间】:2014-08-04 12:05:16
【问题描述】:

我可以有一个 webapi 方法

[Route("someroute")]
public void SomeMethod(string variable1, int variable2, Guid variable3)
{
     //... Code here
}

简单的json

var jsonvariable = new {
    variable1:"somestring",
    variable2:3,
    variable3: {9E57402D-8EF8-45DE-B981-B8EC201D3D8E}
}

然后发帖

HttpClient client = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["SomeURL"]) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.PostAsJsonAsync("someroute", jsonvariable ).Result

来自 javascript,我可以做这样的事情,它可以解决各个属性,但我似乎无法通过 C# 调用来做到这一点

var postData = {
     appUniqueId: appUniqueId
};

$http
   .post('someurl', postData)
   .success(function(response) {
      defer.resolve(response.data);
   });

webapi method
SomeWebMethod(Guid appUniqueId) <-- same name as in postdata

【问题讨论】:

  • 一方面,如果您的 jsonvariable 代码应该是 C#,那么您的语法是错误的。向我们展示您尝试使用的确切代码以及您获得的结果。
  • 对不起。我忘记了上的“新”关键字
  • 我是理论,这应该是可能的。可能导致它失败的原因是缺少标头或格式错误的请求。我建议启动 Fiddler,双向发出请求,并比较原始请求。这应该可以帮助您入门。
  • 这是一个与此问题相关的更深入的问题。我试图发布一个缩写版本来试图得到答案。似乎没有使用“模型”进行模型绑定,这可能是框架限制stackoverflow.com/questions/24212152/…
  • 您的答案在上一个问题中。您应该阅读 Stephan 在他的回答中链接的文章。 asp.net/web-api/overview/formats-and-model-binding/… 特别是这一行:“最多允许从消息正文中读取一个参数......此规则的原因是请求正文可能存储在只能读取一次的非缓冲流中。”

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


【解决方案1】:

你不能像现在这样去做。

如 cmets 和 in this article 中所述,您的方法只能使用 一个 FromBody 参数。因此,这些参数中的一个或没有一个将从您的 JSON 正文中绑定。如果其中任何一个,它可能是它尝试绑定的 guid,只是因为涉及到 web api parameter binding rules

你如何解决这个问题?创建一个描述数据的类。

public class SomeBodyParameters
{
     public string variable1 { get; set; } 
     public int variable2 { get; set; } 
     public Guid variable3 { get; set; } 
} 

那么你的 api 方法将如下所示:

[Route("someroute")]
public void SomeMethod([FromBody]SomeBodyParameters parameters)
{
     //... Code here
}

规定它不会根据类型自动绑定,而是根据您在示例匿名类型中设置的名称。变量 1、变量 2 和变量 3 的名称必须在两个位置匹配。

当您考虑它时,看起来像 JSON 的匿名类型实际上是在传递一种对象,所以实际上这就是您应该接受的。

深思:您如何区分简单的“字符串”和具有像var jsonvariable = new { variable1:"somestring"}; 这样的单数字符串的对象?你基本上不能,两者可能不应该是等价的。

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2016-04-01
    相关资源
    最近更新 更多