【问题标题】:How to read a value in WebAPI sent via WebClient.UploadString?如何读取通过 WebClient.UploadString 发送的 WebAPI 中的值?
【发布时间】:2015-03-24 13:49:20
【问题描述】:

我想将数据发布到 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 动词的查询字符串来调用它。

【问题讨论】:

  • 你必须配置路由。所有这些都失败了,甚至没有查看您尝试传递的参数(POST 的 URL 中的值?真的吗?)
  • 这不是个好主意吗?我喜欢它,因为它更简单。

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


【解决方案1】:

您需要配置您的 Web API 路由以接受 foo 参数。这可能会解决您的问题

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

【讨论】:

  • 如果我不使用查询字符串,我还需要使用它吗?没有权利?但它仍然无法正常工作。查询字符串是理想的,但我可以跳过它。
  • 404 错误可能是一些错误将出现在您的 urI msdn.microsoft.com/en-us/library/d0d3595k(v=vs.110).aspx 中,一旦您更改路由配置并检查您的 uri,此方法将起作用
【解决方案2】:

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] 属性

【讨论】:

    【解决方案3】:
    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中获取数据

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      相关资源
      最近更新 更多