WebApi - 为什么我的帖子变量总是为空?

尼尔·P

我希望能够从我的控制器方法中读取 post 变量。

我目前有以下代码:

[HttpPost]
public IHttpActionResult BuildPartitions([FromBody]string PartitionBuildDate)
{
}

我正在使用以下代码进行测试:

using (HttpClient httpClient = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
        { "PartitionBuildDate", "24-May-2017" }
    };
    var content = new FormUrlEncodedContent(values);
    var response = httpClient.PostAsync("http://localhost:55974/api/Controller/BuildPartitions", content);
    var responseString = response.Result.Content;
}

在线查看,这对于在 C# 中发送和接收 post 变量看起来都是正确的,但是 PartitionBuildDate 变量始终为空。

米杜拉

尝试添加content-type标题。我使用 Newtonsoft JSON.NET 进行 JSON 转换:

string postBody = JsonConvert.SerializeObject(yourDictionary);

var response = client.PostAsync(url, new StringContent(postBody, Encoding.UTF8, "application/json"));

var responseString = response.Result.Content;

此外,在您的 Web API 端,尝试将您的 POST 参数包装在一个类中:

public class PostParameters
{
    public string PartitionBuildDate {get;set;}
}

[HttpPost]
public IHttpActionResult BuildPartitions([FromBody]PostParameters parameters)
{
    //you can access parameters.PartitionBuildDate
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

C#WebApi.SelfHost帖子为空

来自分类Dev

WebAPI C# HttpPost 变量为空

来自分类Dev

为什么我不能通过AngularJS的POST将帖子发送到WebApi?

来自分类Dev

为什么我的HttpPostedFileBase总是为空?

来自分类Dev

webapi接收空参数

来自分类Dev

为什么我无法从我的 Webapi 重定向给定的 url

来自分类Dev

WebAPI HttpContext在ContinueWith()=> tast中为空

来自分类Dev

为什么我的WebAPI RESTful路由会引发404错误?

来自分类Dev

为什么我的变量为空?

来自分类Dev

Azure是否限制我的WebApi?

来自分类Dev

为什么在我的帖子中输入Enter时我的博客帖子条目为空?

来自分类Dev

我如何允许空值被我的WebAPI模型接受?

来自分类Dev

函数参数总是为空为什么?

来自分类Dev

为什么 PropertyChanged 总是为空?

来自分类Dev

Protobuf:WebApi-> JS-解码后的对象为空

来自分类Dev

Angularjs和WebAPI Put方法参数始终为空

来自分类Dev

IFormFile在Asp.Net Core WebAPI中始终为空

来自分类Dev

为什么变量总是为零

来自分类Dev

WebAPI POST方法抛出空异常

来自分类Dev

为什么ASP.NET MVC WebAPI模板使用DbContext作为成员变量?

来自分类Dev

NLog 变量在 WebApi 中更改其值

来自分类Dev

WebAPI传递的post参数为null

来自分类Dev

WebAPI Put返回HTTPResponseMessage为null

来自分类Dev

无法为 Get in WebApi 2 配置路由

来自分类Dev

为什么我的变量elecfirebase总是等于[]?

来自分类Dev

RestFul WebApi中的幂等概念是什么?

来自分类Dev

WebApi自托管的用途是什么?

来自分类Dev

WebApi自托管的用途是什么?

来自分类Dev

WebAPI:为什么这些方法与路由模板匹配?