如何使用asp.net webapi获取Json Post值

Fla*_*ira 14 asp.net post request asp.net-web-api

我正在请求做一个asp.net webapi Post方法,我不能得到一个请求变量.

请求

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) {
        ...
    });
Run Code Online (Sandbox Code Playgroud)

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");

    }
Run Code Online (Sandbox Code Playgroud)

我无法以两种方式获取var1内容...(除非我为此创建一个类)

我该怎么做?

Ben*_*ter 23

第一种方式:

    public void Post([FromBody]dynamic value)
    {
        var x = value.var1.Value; // JToken
    }
Run Code Online (Sandbox Code Playgroud)

请注意,value.Property实际上返回一个JToken实例,以获得它需要调用的值value.Property.Value.

第二种方式:

    public async Task Post()
    {        
        dynamic obj = await Request.Content.ReadAsAsync<JObject>();
        var y = obj.var1;
    }
Run Code Online (Sandbox Code Playgroud)

以上两种工作都使用了Fiddler.如果第一个选项不适合您,请尝试将内容类型设置为application/json以确保JsonMediaTypeFormatter用于反序列化内容.


Bra*_*den 7

在对此进行了一段时间的讨论并尝试了许多不同的事情后,我最终在API服务器上放置了一些断点,并发现请求中填充了键值对.在我知道它们在哪里之后,很容易访问它们.但是,我只发现这个方法可以使用WebClient.UploadString.但是,它可以很容易地工作,并允许您加载任意数量的参数,并非常容易访问它们服务器端.请注意,我的目标是.net 4.5.

客户端

// Client request to POST the parameters and capture the response
public string webClientPostQuery(string user, string pass, string controller)
{
    string response = "";

    string parameters = "u=" + user + "&p=" + pass; // Add all parameters here.
    // POST parameters could also easily be passed as a string through the method.

    Uri uri = new Uri("http://localhost:50000/api/" + controller); 
    // This was written to work for many authorized controllers.

    using (WebClient wc = new WebClient())
    {
        try
        {
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            response = wc.UploadString(uri, login);
        }
        catch (WebException myexp)
        { 
           // Do something with this exception.
           // I wrote a specific error handler that runs on the response elsewhere so,
           // I just swallow it, not best practice, but I didn't think of a better way
        }
    }

    return response;
}
Run Code Online (Sandbox Code Playgroud)

服务器端

// In the Controller method which handles the POST request, call this helper:
string someKeyValue = getFormKeyValue("someKey");
// This value can now be used anywhere in the Controller.
// Do note that it could be blank or whitespace.

// This method just gets the first value that matches the key.
// Most key's you are sending only have one value. This checks that assumption.
// More logic could be added to deal with multiple values easily enough.
public string getFormKeyValue(string key)
{
    string[] values;
    string value = "";
    try
    {
        values = HttpContext.Current.Request.Form.GetValues(key);
        if (values.Length >= 1)
            value = values[0];
    }
    catch (Exception exp) { /* do something with this */ }

    return value;
}
Run Code Online (Sandbox Code Playgroud)

有关如何处理多值Request.Form键/值对的更多信息,请参阅:

http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.110).aspx