如何通过WebClient.UploadString读取Web API发送的值?

时间:2015-03-24 13:49:21

标签: c# asp.net-web-api

我想将数据发布到WebAPI。理想情况下我会这样做:

http:www.myawesomesite.com?foo=bar

作为POST。但对于我的具体问题,我正在尝试使用:

using(var webClient = new WebClient())
{
    client.uploadString("http:www.myawesomesite.com", "POST", "foo=bar");
}

But that converts "foo=bar" to a bye array。好的,我只是想让它在这一点上起作用。

我的Web API控制器如下所示:

[HttpPost]
public void MashPotatos(string foo)
{
    potatoMasher.Mash(foo);
}

但我得到The remote server returned an error: (404) Not Found.首先,我认为WebAPI会自动为我提供数据,即使它是在请求正文中。但更重要的是,我只是希望能够让它发挥作用。

理想情况下,我希望将WebAPI方法保留为一种形式,以便您仍然可以使用带有POST动词的查询字符串来调用它。

3 个答案:

答案 0 :(得分:1)

您需要配置您的网址API路线以接受foo参数。可能会解决您的问题

config.Routes.MapHttpRoute(name: "newont",
                routeTemplate: "api/{controller}/{foo}",
                defaults: new { controller = "Controllername", foo= "foo"}
            );

答案 1 :(得分:0)

here是一篇可能对某些人有帮助的帖子。对我来说,我只需要这样做:

using(var webClient = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    client.uploadString("http:www.myawesomesite.com", "POST", "foo=bar");
}

[HttpPost]
public void MashPotatos([FromBody]string foo)
{
    potatoMasher.Mash(foo);
}

我决定不使用查询字符串进行POST,因为它似乎违反了convention,但还有[FromUri]属性

答案 2 :(得分:0)

public string GetData(){
string jsonResponse = string.Empty;using (WebClient client = new WebClient()){client.Headers[HttpRequestHeader.ContentType] = "application/json";
  jsonResponse = client.UploadString(baseuri, "POST", @"{personId:""1"", startDate:""2018-05-21T14:32:00"",endDate:""2018-05-25T18:32:00""}");  
return JsonConvert.DeserializeObject<Model>(jsonResponse);}}
  

@ “{PERSONID:” “1””,   开始日期: “” 2018-05-21T14:32:00 “”,结束日期: “” 2018-05-25T18:32:00 “”}

这是一个JSON自定义字符串,或者您可以在API端序列化该对象

<强> HttpPost

    public string Metod(Something data)
    {
        DateTimeOffset sDate = DateTimeOffset.Parse(data.date1);
        DateTimeOffset eDate = DateTimeOffset.Parse(data.date2);
        return _someService.GetService(data.Id, sDate, eDate);
    }

然后我们转到服务并从DB获取数据

相关问题