4

I have webapi and her method:

[HttpPost, HttpGet]
[ActionName("GetData")]
public MyData GetData([FromUri] MyData data)
{
  return datamanager.get(data);
}

How do I invoke this method? I.e. how do I send data parameter through query part of URL?

To invoke get method which takes no parameters I use following code:

public static async Task<myClassl> GetData()
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://sasa.com");
    HttpResponseMessage response = await client.GetAsync("api/GetData");
    myClassl data = await response.Content.ReadAsAsync<myClassl>();

    return data ;
}

Thanks.

0

1 Answer 1

1

Try the following solution:

HttpClient client = new HttpClient();
string baseApiAddress = ConfigurationManager.AppSettings["baseApiAddress"];
client.BaseAddress = new Uri(baseApiAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response=client.GetAsync("/api/GetData",data, new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{
var mydata = response.Content.ReadAsAsync<MyData>().Result;
}
else
{
Debug.WriteLine(response.ReasonPhrase);
}
Sign up to request clarification or add additional context in comments.

4 Comments

When I use GetAsync I hace error in compilation, when i use PostAsync in webapi i have null parameter
Sorry I forgot to tell to add the next lines of code inside your App.config file inside configuration (localhost:23602 is just an example use your port) <appSettings> <add key="baseApiAddress" value="localhost:23602/"> </appSettings>
i am getting error: Error The best overloaded method match for 'System.Net.Http.HttpClient.GetAsync(string, System.Net.Http.HttpCompletionOption)' has some invalid arguments
GetAsync does not have a data param; most probably the params must be sent in URI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.