user1873073
user1873073

Reputation: 3670

How to read a value in WebAPI sent via WebClient.UploadString?

I want to POST data to WebAPI. Ideally I would just do:

http:www.myawesomesite.com?foo=bar

As a POST. But to my specific question, I am trying to use:

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

But that converts "foo=bar" to a bye array. Okay fine, I'm just trying to get it to work at this point.

My Web API controller looks like this:

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

But I get The remote server returned an error: (404) Not Found. First off, I thought WebAPI would automatically grock that data for me even if it was in the body of the request. But more importantly, I just want to be able to get it to work.

Ideally, I'd like to leave the WebAPI method in a form such that you can still invoke it by using a query string with a POST verb.

Upvotes: 0

Views: 1970

Answers (3)

maria
maria

Reputation: 1

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""}

It's a JSON custom string, or you can serialize the object here on the API side

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);
    }

Then we go to the service and get data from DB

Upvotes: 0

user1873073
user1873073

Reputation: 3670

Well here is a post that might be helpful to some. For me I just had to do:

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

and

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

I decided against doing a POST with a query string as it seems to go against convention but there is also a [FromUri] attribute

Upvotes: 0

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

you need to configure your web API route to accept a foo parameter.May be this will solve your issue

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

Upvotes: 1

Related Questions