[英]How to read a value in WebAPI sent via WebClient.UploadString?
我想将数据发布到WebAPI。 理想情况下,我会这样做:
http:www.myawesomesite.com?foo=bar
作为POST。 但是对于我的特定问题,我尝试使用:
using(var webClient = new WebClient())
{
client.uploadString("http:www.myawesomesite.com", "POST", "foo=bar");
}
但这会将“ foo = bar”转换为再见数组 。 好的,我只是想让它开始工作。
我的Web API控制器如下所示:
[HttpPost]
public void MashPotatos(string foo)
{
potatoMasher.Mash(foo);
}
但是我得到The remote server returned an error: (404) Not Found.
首先,我认为WebAPI会自动为我保存该数据,即使该数据位于请求正文中也是如此。 但更重要的是,我只希望能够使其正常工作。
理想情况下,我希望将WebAPI方法保留为某种形式,以便您仍可以通过使用带有POST动词的查询字符串来调用它。
您需要配置您的Web API路由以接受foo参数。也许这将解决您的问题
config.Routes.MapHttpRoute(name: "newont",
routeTemplate: "api/{controller}/{foo}",
defaults: new { controller = "Controllername", foo= "foo"}
);
好吧, 这是一篇可能对某些人有用的帖子。 对我来说,我只需要做:
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,因为这似乎违反了约定,但是还有一个[FromUri]属性
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”“,startDate:”“ 2018-05-21T14:32:00”“,endDate:”“ 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);
}
然后我们去服务并从数据库中获取数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.