如何在 WebAPI 中获取 POST 数据? [英] How to get POST data in WebAPI?

查看:42
本文介绍了如何在 WebAPI 中获取 POST 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以以下形式向服务器发送请求:

I'm sending a request to server in the following form:

http://localhost:12345/api/controller/par1/par2

请求被正确解析为如下方法:

The request is correctly resolved to a method like:

[HttpPost]
public void object Post(string par1, string par2)

但是,我通过请求内容传递了额外的数据.如何检索这些数据?

However, I pass additional data through the request content. How can I retrieve these data?

举个例子,假设请求是从表单发送的:

For the sake of example, let's say, that the request is sent from the form:

<form action="http://localhost:12345/api/controller/par1/par2" method="post">
    <input type="hidden" name="data" value="value" />
    <input type="submit" name="submit" value="Submit" />
</form>

推荐答案

来自这个问题的答案:如何使用 asp.net webapi 获取 Json Post 值

  1. 使用参数绑定自动解析;请注意,dynamicJToken 组成,因此是 .Value 访问器.

  1. Autoparse using parameter binding; note that the dynamic is made up of JToken, hence the .Value accessor.

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

  • 读起来就像Request.RequestUri.ParseQueryString()[key]

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

  • 与#2 相同,只是不是异步的 (?) 所以你可以在辅助方法中使用它

  • Same as #2, just not asynchronously (?) so you can use it in a helper method

    private T GetPostParam<T>(string key) {
        var p = Request.Content.ReadAsAsync<JObject>();
        return (T)Convert.ChangeType(p.Result[key], typeof(T)); // example conversion, could be null...
    }
    

  • Caveat -- 需要媒体类型 application/json 以触发 JsonMediaTypeFormatter 处理.

    Caveat -- expects media-type application/json in order to trigger JsonMediaTypeFormatter handling.

    这篇关于如何在 WebAPI 中获取 POST 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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