skip to Main Content

I am very new to the whole consept of API’s. So far, I managed to build a web api that has GET,POST,PUT and DELETE methods.

Now, from an ASP.NET project, I try to finally use my web api.

Here’s what I do for GET method:

string info = new WebClient() { }.DownloadString("https://mywebapisite.com/item/" + id);
Item item = JsonConvert.DeserializeObject<Item>(info);

This functions all fine. As you can see, all the GET method needs is an id.

However, for the POST method, I have no clue what to do.
I can create a new Item instance, but don’t know what to do with it.

By the way, I also used ASP.NET to make my web.api.
There is a built-in feature in ASP.NET 5 called Swagger. It can perform all the tasks very succesfully. Is there like a code-behind for what Swagger does.

PS: I know that this question must be very common and basic. If you could refer me to another question in stackoverflow or simply tell me what to search on google I would appreciate it. (As you may guess, I don’t even know what to search for)

3

Answers


  1. pseudo code to consume post request in C#

    var requestObj = GetDummyDataTable();
    
    using (var client = new HttpClient())  
    {  
        // Setting Base address.  
        client.BaseAddress = new Uri("https://localhost:8080/");  
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
        HttpResponseMessage response = new HttpResponseMessage();  
    
       // HTTP POST  
       response = await client.PostAsJsonAsync("api/product", requestObj).ConfigureAwait(false);  
        
       if (response.IsSuccessStatusCode)  
       {  
          // Reading Response.  
          string result = response.Content.ReadAsStringAsync().Result;  
          var responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
       }  
    }  
    
    Login or Signup to reply.
  2. You can refer the following code to call the API using HttpClient:

    ////using System.Net.Http.Headers;
    ////using System.Text;
    using (var client = new HttpClient())
    {
        var requesturi = "https://localhost:7110/api/ToDo/relativeAddress";
    
        var item = new TestUserViewModel()
        {
            Name = "John Doe",
            Age = 33
        };
        ////using System.Text.Json;  // use JsonSerializer.Serialize method to convert the object to Json string. 
        StringContent content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");
    
        //HTTP POST
        var postTask = client.PostAsync(requesturi, content);
        postTask.Wait();
    
        var result = postTask.Result;
        if (result.IsSuccessStatusCode)
        {
            var Content = await postTask.Result.Content.ReadAsStringAsync();
    
            return RedirectToAction("Privacy");
        }
    }
    

    The API method like this:

    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    { 
        [HttpPost]
        [Route("relativeAddress")]
        public string GetAddress([FromBody] TestUserViewModel testUser)
        {
            return "Address A";
        }
    

    And the result like this:

    enter image description here

    You can also refer this link to set the Content-Type.

    Login or Signup to reply.
  3. You seem a little bit lost, and I get it. Api learning path is kinda weird, I recommend you watch a tutorial (My favorite https://www.youtube.com/playlist?list=PLLWMQd6PeGY0bEMxObA6dtYXuJOGfxSPx)
    But if you need code asap, you could refer the following code.
    Ps: The others answers are really good!

            using System.Net.Http;
            using System.Net.Http.Headers;
                
            public class ApiHelper
                    {
                        public HttpClient ApiClient { get; set; }
                
                        public void InitializeClient()
                        {
                            ApiClient = new HttpClient();
                            ApiClient.BaseAddress = new Uri("https://mywebapisite.com/");
                            ApiClient.DefaultRequestHeaders.Accept.Clear();
                            ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        }
                        public async Task PostSomething(FormUrlEncodedContent data)
                        {
                           using (HttpResponseMessage response = await ApiClient.PostAsync("/item",data)
                           {
                             var result = await response.Content.ReadAsAsync<string>();
                             
                           }
                        }
                    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search