locked
How to make proper Query and Post or CRUD request for Web Api with parameters RRS feed

  • Question

  • User-1980778524 posted

    Hi,

    I am using Fiddler to do testing. The following url seems to be alright.

    But I am not sure when using a Mobile Client with HttpClient for testing. In order to avoid confusion, I need your help for web api.

    I have created the Api Controller and use specific routing.

    1) Api Controller name : UserController
    2) Please help to verify are these Url properly build for mobile client make the respective requests with HttpClient?
    3) is uri case sensitive for web api? like User and user, GetUserById and getuserbyid (Lower case)


    A)--------------------------------------------------

      [HttpGet]
      [Route("api/User/GetUserById/{Id}")]      
      public HttpResponseMessage GetUserById(int id){}
     
    Task : get a user by Id

    use which url?

     var url = "http://domainname.com/api/user/3";

      or
     var url = "http://domainname.com/api/user/?id=3";
     var uri = new Uri(url);

    B)-----------------------------------------------------------

     [HttpGet]
     [Route("api/User/GetUserByName/{contact}")]
     public HttpResponseMessage GetUserByName(string contact){}
     

     Task : Get a user by Name

    use which url?

     var url = "http://domainname.com/api/user/GetUserByName/Smith";

     or
     var url = "http://domainname.com/api/user/GetUserByName/?contact=Smith";
     var uri = new Uri(url);


    C) ------------------------------------------------------

    C1)
     
      [HttpPost]

     [Route("api/User/PostContact")]
      public HttpResponseMessage PostContact([FromBody] User contact){}

     Task : using HttpClient to Post data

     Controller method : using :[FromBody]


    -- build the Url

     var url = "http://domainname.com/api/user/";
     var uri = new Uri(url);


    ---use url for Client send POST using PostAsync ( PutAsync will be similar?)

     HttpClient client = new HttpClient();
     var url = "http://domainname.com/api/user/";
     var uri = new Uri(url);

     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

     var json = JsonConvert.SerializeObject(Usr);
     var content = new StringContent(json, Encoding.UTF8, "application/json");
     HttpResponseMessage response = await client.PostAsync(uri, content);


    C2) use Post or Query when [FromBody] Change to [FromUri]?

      [HttpPost]
      public HttpResponseMessage PostContact([FromBody] User contact){}

    Thanks.

    Wednesday, May 3, 2017 5:42 AM

All replies

  • User475983607 posted

    SkyDriving

    2) Please help to verify are these Url properly build for mobile client make the respective requests with HttpClient?

    When you specify the route using an attribute like this... 

     [HttpGet]
      [Route("api/User/GetUserById/{Id}")]       
      public HttpResponseMessage GetUserById(int id){}

    Then the URL is exactly as written.

    http://domainname.com/api/User/GetUserById/3

    SkyDriving

    3) is uri case sensitive for web api? like User and user, GetUserById and getuserbyid (Lower case)

    No, URL are not case sensitive but the routes values are when using a case sensitive language like C# and invoking a comparison.

    Below you will find a working example of an client async post.  I pulled the source code from a link I provided  in another one of your threads with the same type of subject matter. Please set aside the necessary time to go through the link and the associated navigation on the left. There is a lot of content, some advanced.  The learning process should take several days if not weeks to go through and understand.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

    Controller

            // POST: api/Widget
            public IHttpActionResult Post([FromBody]Widget widget)
            {
                widget.Id = Guid.NewGuid();
                return CreatedAtRoute("GetById", new { id = widget.Id }, widget); ;
            }

    Model

        public class Widget
        {
            public Guid Id { get; set; }
            public string Name { get; set; }
            public string Color { get; set; }
        }

    Async Client

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net.Http;
    using System.Net.Http.Headers;
    
    namespace ApiClient
    {
        class Program
        {
            // New code:
            static HttpClient client = new HttpClient();
    
            static void Main(string[] args)
            {
                RunAsync().Wait();
    
            }
    
            static async Task RunAsync()
            {
                // New code:
                client.BaseAddress = new Uri("http://localhost:30387/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                Widget w = new Widget() { Color = "Red", Name = "My Widget" };
    
                var url = await CreateProductAsync(w);
                Console.WriteLine($"Created at {url}");
    
                Console.ReadLine();
            }
    
    
            static async Task<Uri> CreateProductAsync(Widget product)
            {
                HttpResponseMessage response = await client.PostAsJsonAsync("api/widget", product);
                response.EnsureSuccessStatusCode();
    
                // Return the URI of the created resource.
                return response.Headers.Location;
            }
        }
    
    
        public class Widget
        {
            public Guid Id { get; set; }
            public string Name { get; set; }
            public string Color { get; set; }
    
        }
    }
    

    I also suggest that you take some time to learn HTTP basics as Web API is built on HTTP.  You should learn HTTP first as it will help with your Web API understanding.

    Wednesday, May 3, 2017 4:45 PM