如何获得的Json值后用asp.net的WebAPI [英] How to get Json Post Values with asp.net webapi

查看:176
本文介绍了如何获得的Json值后用asp.net的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做的请求做一个asp.net的WebAPI邮政法,我不beeing能得到一个请求变量。

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 实例,以便让您需要调用<值code> 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;
    }

无论使用招上述工作。如果第一个选项是不是为你工作,尽量将内容类型设置为应用程序/ 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.

这篇关于如何获得的Json值后用asp.net的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆