如何使用 asp.net webapi 获取 Json Post 值 [英] How to get Json Post Values with asp.net webapi
问题描述
我正在请求执行一个 asp.net webapi Post 方法,但我无法获得请求变量.
i'm making a request do a asp.net webapi Post Method, and i'm not beeing able to get a request variable.
请求
jQuery.ajax({ url: sURL, type: 'POST', data: {var1:"mytext"}, async: false, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=UTF-8' })
.done(function (data) {
...
});
WEB API Fnx
[AcceptVerbs("POST")]
[ActionName("myActionName")]
public void DoSomeStuff([FromBody]dynamic value)
{
//first way
var x = value.var1;
//Second way
var y = Request("var1");
}
我无法以两种方式获取 var1 内容...(除非我为此创建了一个类)
i Cannot obtain the var1 content in both ways... (unless i create a class for that)
我该怎么做?
推荐答案
第一种方式:
public void Post([FromBody]dynamic value)
{
var x = value.var1.Value; // JToken
}
请注意,value.Property
实际上返回一个 JToken
实例,因此要获取它的值,您需要调用 value.Property.Value
.
Note that value.Property
actually returns a JToken
instance so to get it's value you need to call value.Property.Value
.
第二种方式:
public async Task Post()
{
dynamic obj = await Request.Content.ReadAsAsync<JObject>();
var y = obj.var1;
}
上述两项工作都使用 Fiddler.如果第一个选项不适合您,请尝试将内容类型设置为 application/json
以确保使用 JsonMediaTypeFormatter
反序列化内容.
Both of the above work using Fiddler. If the first option isn't working for you, try setting the content type to application/json
to ensure that the JsonMediaTypeFormatter
is used to deserialize the content.
这篇关于如何使用 asp.net webapi 获取 Json Post 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!