HttpClient - REST - Interface / GET / POST

Markus Freitag 3,791 Reputation points
2023-09-04T17:09:34.7833333+00:00

Hello,

Is there a simple way to simulate a GET and POST message?

I do not want a SQL database, unnecessary overkill.

I just want to test the request where a successful response comes back.

Thanks for any tips in advance.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-3

_REST_INTERFACE_1

Developer technologies Windows Forms
Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2023-09-05T08:08:33.2933333+00:00

    Hi @Markus Freitag,

    As per your requirement, you just want to create a very simple test, just refer to the getting started documentation.

    When you create a new WebAPI, you will find get and POST methods in ValuesController.

    You can follow the docs and set some test data according to the client so you don't need to connect to the database.

    You also need to know how to call the Web API from a .NET client.

    Create a Web API Project

    Call a Web API From a .NET Client (C#)

    Below is the demo I wrote, you can refer to it.

    WebAPI

    public class ValuesController : ApiController
    {
       
        public class RequestWorkorder
        {
            public string Program { get; set; }
            public string Workorder { get; set; }
        
        }
        RequestWorkorder[] requestWorkorders = new RequestWorkorder[]
       {
            new  RequestWorkorder { Program = "1", Workorder = "a" },
            new  RequestWorkorder { Program = "2", Workorder = "b", },
            new  RequestWorkorder{ Program = "3", Workorder = "c"}
       };
        public IEnumerable<RequestWorkorder> GetAllProducts()
        {
            return requestWorkorders;
        }
    
        public IHttpActionResult GetProduct(string program)
        {
            var product = requestWorkorders.FirstOrDefault((p) => p.Program == program);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
       
        
        public IHttpActionResult Post([FromBody] RequestWorkorder requestWorkorder)
        {
            List<RequestWorkorder> requestWorkorders =new List<RequestWorkorder>();
            requestWorkorders.Add(requestWorkorder);
            return Ok();
        }
    
    
    }
    

    .NET client

    public class RequestWorkorder
    {
        public string Program { get; set; }
        public string Workorder { get; set; }
    
    }
    
    
    RequestWorkorder p = new RequestWorkorder()
    
    {
        Program = "4",
        Workorder = "D"
    };
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://localhost:44377/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        string authorization = $"{""}:{""}";
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "");
        //GET Method
        HttpResponseMessage response = await  client.GetAsync("api/Values");
        if (response.IsSuccessStatusCode)
        {
            List<RequestWorkorder> requestWorkorder = null;
            requestWorkorder = await response.Content.ReadAsAsync<List<RequestWorkorder>>();
            Console.WriteLine("Id:{0}\tName:{1}", requestWorkorder[0].Program, requestWorkorder[0].Workorder);
    
        }
        //POST Method
        HttpResponseMessage response1 = await client.PostAsJsonAsync("api/Values", p);
    
        if (response1.IsSuccessStatusCode)
        {
    
           
            Console.WriteLine("Success");
        }
        else
        {
            Console.WriteLine("Internal server Error");
        }
    }
    

    User's image

    User's image

    Best regards,

    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Johan Smarius 470 Reputation points MVP
    2023-09-04T20:02:12.5866667+00:00

    You can mock the behaviour of the HttpClient. Through the mock, you can test different responses. Perhaps this article will help you a bit: https://chrissainty.com/unit-testing-with-httpclient/

    0 comments No comments

  2. SurferOnWww 4,631 Reputation points
    2023-09-05T01:27:55.55+00:00

    Is there a simple way to simulate a GET and POST message?

    I do not want a SQL database, unnecessary overkill.

    Yes.

    Just create the WebAPI project according to the tutorial. You may forget about the Azure, SQL Server and others mentioned in the tutorial.

    Create the project

    The project includes the ValuesController, as follows:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace WebAPI2.Controllers
    {
        public class ValuesController : ApiController
        {
            // GET api/values
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET api/values/5
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/values
            public void Post([FromBody] string value)
            {
            }
    
            // PUT api/values/5
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE api/values/5
            public void Delete(int id)
            {
            }
        }
    }
    

    You can call the above action methods from the HttpClient.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.