question

MarkusFreitag-0088 avatar image
0 Votes"
MarkusFreitag-0088 asked MarkusFreitag-0088 commented

REST interface, C#

Hello,
I need to send this data via a REST interface.

 {
   "actorname": "Marking",
   "taskname": "2022-06-10-O424",
   "stepname": "EXECUTION_2",
   "parameters": [
     { "name": "parameter A", "value": 73.1 },
     { "name": "parameter B", "value": 12 }
     { "name": "parameter C", "value": 173.1 },
     { "name": "parameter D", "value": 112 }
     { "name": "parameter E", "value": 273.1 },
     { "name": "parameter F", "value": 312 }
   ]
 }

How can I achieve this?
How can I test this?

I think I have to send it by POST, because I have data with a relationship in it. 1 to n link.
What is the best way to achieve the goal?

GET is, I ask for infos.
POST, I must send a object, structure...
PUT, when must I need PUT?

Is there a test server where I can see what I have sent, where I can generate test messages.

Thanks for your help in advance.
Best regards

dotnet-csharpdotnet-aspnet-webforms
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

You're asking REST fundamentals which are openly covered in any beginning level tutorial. I recommend starting with the following.

Tutorial: Create a web API with ASP.NET Core

PUT, when must I need PUT?

PUT is used for updating a resource.

Is there a test server where I can see what I have sent, where I can generate test messages.

PostMan is a very good testing utility for REST services.

https://www.postman.com/

Or you can build a Web API application rather easily.

By the way, your JSON is invalid. It's missing commas.

  {
    "actorname": "Marking",
    "taskname": "2022-06-10-O424",
    "stepname": "EXECUTION_2",
    "parameters": [
      { "name": "parameter A", "value": 73.1},
      { "name": "parameter B", "value": 12 },
      { "name": "parameter C", "value": 173.1},
      { "name": "parameter D", "value": 112 },
      { "name": "parameter E", "value": 273.1},
      { "name": "parameter F", "value": 312 }
    ]
  }







1 Vote 1 ·

Thanks,
Do you know a good sample code for the server, for testing. Postman is not so easy.

Yes that's look good.
first-web-api



0 Votes 0 ·
AgaveJoe avatar image
1 Vote"
AgaveJoe answered MarkusFreitag-0088 commented

It is not a web application. It is a C# desktop application.

Then fix the tags! You tagged this post as MVC and Web Forms which are web applications. Plus a REST service is a web application!

The questions, what is the best way to create a server? A mock server?

This information is covered above with example code and links. Can you explain why you are unable to perform these very basic tasks?

My machine connects to a SCADA MES system.

If you need help with communicating with a SCADA MES system then SCADA MES is a better place to get support.







· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.



Thanks for the answer.

Can you explain why you are unable to perform these very basic tasks?

Unfortunately not! I have to make a request and evaluate the answer correctly.
Since the customer does not provide me with anything, I have to create a test server, mocj server. It doesn't matter if this is done with WebApi or Desktop.
I should be able to make the request and easily generate a test response. My goal.
This seems to be possible under VS2022, not under VS2019


 //Request
 try
 {
     using (HttpClient client = new HttpClient())
     {
 #endif
         client.BaseAddress = new Uri(CfgSystem.Baseaddress);
         client.Timeout = new TimeSpan(0, 0, CfgSystem.Timeout);
    
         string authorization = $"{CfgSystem.Username}:{CfgSystem.Password}";
         Trace.Writeline($"RequestNewOrder, authorization='{authorization}'");
    
         client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(authorization)));
         urlParameters = CfgSystem.UrlGetOrderData.Replace("{orderId}", orderId);
        
         response = client.GetAsync(urlParameters).Result;  
     }
    
 //Response
 if (response.IsSuccessStatusCode)
     {
         var dataObjects = response.Content.ReadAsStringAsync();
         ResponseOrder res = JsonConvert.DeserializeObject<ResponseOrder>(dataObjects.Result);
    
    
 //How would you create the mock server under VS2019?



0 Votes 0 ·
AgaveJoe avatar image AgaveJoe MarkusFreitag-0088 ·

Since the customer does not provide me with anything, I have to create a test server, mocj server. It doesn't matter if this is done with WebApi or Desktop.

Unfortunately, your response does not make any sense. Five days ago you confirmed ZhiLv-MSFT's GitHub Web API project returned expected results. This is the mock server. As far as I know the mock server is complete, right???

This seems to be possible under VS2022, not under VS2019

This statement is not true. The only thing I can think of is you did not install the ASP.NET and web development workload.

213350-capture.png


What exactly is the problem you are trying to solve? The last bit of code you shared uses HttpClient and Basic Authentication. Is the problem you need to implement basic authentication in the Web API project? Or do you need an HttpClient example for ZhiLv-MSFT's GitHub Web API project?

I dropped a basic Web API and Console client project on GitHub. It uses the data model in your first post. Feel free to modify the code as needed. If you need other feature like basic authentication or help with created a Post, Put, etc., then you must tell us exactly what you need. Otherwise we have no way of knowing what you are thinking.

https://github.com/mjgebhard/WebApiDemo




1 Vote 1 ·
capture.png (62.5 KiB)

You are right! ASP.NET was not installed.

Your project looks good. Thank you very much.

What is the best way to debug this? I have to start the server first.




   await client.GetAsync("api/values");  call from client
        
           // GET api/values
                 [HttpGet]
                 public List<ResponseOrder> Get()
                 {
                     return model;
                 }
       I get the whole model. I think it is clear.
        
        
       // GET api/values/21412 --> is that right?
     Yes I want now to say Get  https://localhost:44328/GetOrder='21412'
        
     Yes I want now to say Post  https://localhost:44328/Post=object...
        
     Yes I want now to say Push  https://localhost:44328/Push=object ..update




Maybe you can make some short examples.
Then I have everything and can quickly adjust the test answers.

If you can still show the authorization, it would be great! Thanks in advance!


213721--1.png


213647--2.png




0 Votes 0 ·
-1.png (109.3 KiB)

How can I get this to run mode on another PC? No development environment available.
What do i have to do, what would i have to install?

213696-0033.png


0 Votes 0 ·
0033.png (12.3 KiB)
 public static async Task<ResponseOrder> GetData2(string id)
 {
  HttpResponseMessage response = await client.GetAsync($"api/values/{id}");
  ResponseOrder data = new ResponseOrder();
  string rawJson = string.Empty;
    
  if (response.IsSuccessStatusCode)
  {
      //Display the raw data
      rawJson = await response.Content.ReadAsStringAsync();
      Console.WriteLine(rawJson);
      Console.WriteLine();
    
      //Deserialize into the List<ResponseOrder> type
      data = JsonConvert.DeserializeObject<ResponseOrder>(rawJson);
  }
  return data;
 }

Is there anything else you can say?
I have no ASYNC function from which I call this function.

  public void GetData()
  {
    //Can I call an ASYNC from there?
  }

I call then like this, right?

 static void Main(string[] args)
 {
  //Configure HttpClient
  client = new HttpClient();
  client.BaseAddress = new Uri("https://localhost:44328");
    
  //Make the HTTP request
  ResponseOrder data2 = GetData2("2022-06-10-O425").GetAwaiter().GetResult();            
  Console.WriteLine(data2.taskname);
 }








0 Votes 0 ·
Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered MarkusFreitag-0088 commented

in REST

GET is used to fetch entity via a url query string
POST is used add/create an entity
PUT is used to update/replace an entity
PATCH is used for partial updates
DELETE is used to delete an entity

those are just the methods. the api should define what the body data should be and any required headers.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks,
Do you know a good sample code.

0 Votes 0 ·
ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered MarkusFreitag-0088 edited

Hi @MarkusFreitag-0088,

How can I achieve this?
How can I test this?

If you are using Asp.net core API, you can create an Asp.net core Web API project, by default in asp.net 6, it has configured with Swagger, then after creating the API controller, you could use the swagger UI to test the API methods.

I think I have to send it by POST, because I have data with a relationship in it. 1 to n link.
What is the best way to achieve the goal?

To create the API or Rest Service, first, you need to create model based on the JSON data, you can search "json to c# class online" using Google or Bing, there have some online tools to generate the C# class based on the JSON data. And the Model like this:

 //required using System.ComponentModel.DataAnnotations;
 public class TodoModel
 {
     [Key]
     public int TodoId { get; set; }
     public string actorname { get; set; }
     public string taskname { get; set; }
     public string stepname { get; set; }
     public List<Parameter> parameters { get; set; }
 }
 public class Parameter
 {
     [Key]
     public int PId { get; set; }
     public string name { get; set; }
     public double value { get; set; }
 }

Then, right click the Controllers folder-> Add-> New Scaffolded Item.. , in the Popup window, Select API -> API Controller with actions, using Entity Framework. Finally, click the Add button:

210781-image.png

After that, it will generate the Controller with the CRUD and Put methods:

210765-image.png

Then, you can enable migration to generate the database and the table.

PUT, when must I need PUT?

The Put method is used to update the entity. Refer Web API Overview

210715-image.png

Running the application, and test the API method using Swagger UI:

210647-2.gif

Reference:

first-web-api/samples

Tutorial: Get started with EF Core in an ASP.NET MVC web app(This is similar in the API project)


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.

Best regards,
Dillion


image.png (22.3 KiB)
image.png (188.8 KiB)
image.png (23.8 KiB)
2.gif (2.2 MiB)
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

First, thanks for your help!

Then, right click the Controllers folder-> Add-> New Scaffolded Item

I use VS2019, C#, .NET4.7.2
Is it possible? Looks good, but I can't create it. Can you help me please?

Can you make a screenshot, which project you use?
210678-select-what.png



Can you share the project?

0 Votes 0 ·
select-what.png (86.5 KiB)
ZhiLv-MSFT avatar image ZhiLv-MSFT MarkusFreitag-0088 ·

Hi @MarkusFreitag-0088,

Is it possible? Looks good, but I can't create it. Can you help me please?

Can you make a screenshot, which project you use?

In my previous reply, the sample is an Asp.net core API application (use VS 2022), instead of the .Net 4.7.2 asp.net project.

210833-image.png

To create .Net 4.7.2 API, you could select the .Net Framework template.

210727-image.png

Then, in the API project's Models folder to add the Model and add the API controller in the Controllers folder.

But, as far as I know, in the .NET 4.7.2 API, it doesn't configure swagger, so, you need to use PostMan to test the API method.

0 Votes 0 ·
image.png (22.9 KiB)
image.png (33.9 KiB)

but, as far as I know, in the .NET 4.7.2 API, it doesn't configure swagger, so, you need to use PostMan to test the API method.

Can you please still publish how you can configure the test answers under Postman?
Would be very nice of you. Is this freeware?
Questions about C#, answers via Postman.

I don't have Visual Studio 2022. I need to develop it under VS2019. Can you please help me with this.
GET and Post. Message.

Can you upload the project? I must have done it once. It's difficult if you've never done it before. Thanks for your support.

0 Votes 0 ·
ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered MarkusFreitag-0088 commented

Hi @MarkusFreitag-0088,

Can you please still publish how you can configure the test answers under Postman?
Would be very nice of you. Is this freeware?
Questions about C#, answers via Postman.

I don't have Visual Studio 2022. I need to develop it under VS2019. Can you please help me with this.
GET and Post. Message.

Can you upload the project? I must have done it once. It's difficult if you've never done it before. Thanks for your support.

Since I don't have VS 2019 on my machine, I will create a .Net 4.7.2 API application using VS 2022, the steps and code should work well on VS 2019.

  1. Open VS, in the Create a new Project window, use the ASP.NET Web Application (.NET Framework) template to create a Web API project.

    211105-image.png

  2. In the Web API project, in the Models folder, add the following code:

      public class TodoModel
         {
             [Key]
             public int TodoId { get; set; }
             public string actorname { get; set; }
             public string taskname { get; set; }
             public string stepname { get; set; }
             public List<Parameter> parameters { get; set; }
         }
         public class Parameter
         {
             [Key]
             public int PId { get; set; }
             public string name { get; set; }
             public double value { get; set; }
         }
    
  3. Right click the Controllers folder, select Add -> Controller or New Scaffolded Item

    211027-image.png

    In the Add New Scaffolded Item window, select the API controller as below:

    211095-image.png

    Then, select the model and Dbcontext (if there doesn't have a dbcontext, you can click the plus icon to add a new one)

    211124-image.png

    [Note] After clicking the Add button, it might need to install some package to auto generate the relate controller. If meet any error, retry this steps again or based on the error message to install the package by yourself.

    Then the result as below: the controller has the CRUD and Put method.
    211077-image.png

  4. Runing the application, the result as below:
    211096-image.png

  5. Open Postman, according the application url and the API route to send the JSON data, like this:
    [Note] When using Postman, the method we need to select Post, and to transfer JSON data, in the request body, we need to choose raw and JSON:

    211132-image.png

    The finally result as below:
    211085-2.gif

You could view the source code from here:

211142-todomodel.txt, 211048-todocontroller.txt, 211151-apidbcontext.txt


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.

Best regards,
Dillion


image.png (49.1 KiB)
image.png (83.2 KiB)
image.png (29.3 KiB)
image.png (8.4 KiB)
image.png (205.0 KiB)
image.png (207.9 KiB)
image.png (57.8 KiB)
2.gif (1.4 MiB)
todomodel.txt (649 B)
todocontroller.txt (3.0 KiB)
· 8
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,
Thanks you very much for your help. Looks good.
Some questions

211163-thanks-openitems.png


My packages. Attachment 211182-packages.txt


We are almost at the goal!

Not possible to install it. Any idea for me? Not so easy.

![211165-not-possible-however-05.png][3]


0 Votes 0 ·
ZhiLv-MSFT avatar image ZhiLv-MSFT MarkusFreitag-0088 ·

Hi @MarkusFreitag-0088,

First, about the TodoModel class, you can create it in the Models folder.

Second, about the Microsoft.EntityFrameworkCore.InMemory package, this package apply to the Asp.net core application, instead of the .Net Framework application, so you can't install/use it in your .Net 4.7.2 application. Try to use a SQL server database to store the data.

0 Votes 0 ·

Hello,

Thanks!

First, about the TodoModel class, you can create it in the Models folder.


211672-no.png



I think it does not work under VS2019. I don't know what I need to reinstall. I don't have a ToDO model in the list. Very difficult.

Is there a way that you upload the whole project? OneDrive?

0 Votes 0 ·
no.png (85.5 KiB)
Show more comments

You make a perfect instruction. Thanks!


211678--server-client-04.png



1 --> is server
2 --> is client

Can you show me. how you make the server with Postman?

Client with C#
Do you see a way that I can make this work under VS2019?



0 Votes 0 ·
-server-client-04.png (220.3 KiB)
AgaveJoe avatar image AgaveJoe MarkusFreitag-0088 ·

Can you show me. how you make the server with Postman?

See the PostMan support documentation.

Setting up mock servers

Do you see a way that I can make this work under VS2019?

Your question is not clear. Visual Studio is a development environment and code editor. Are you actually asking how to create a Web API client in the .NET Framework?

Get Started with ASP.NET Web API 2 (C#)
Action Results in Web API 2


1 Vote 1 ·
Show more comments

Thank you for your help and your answers.

0 Votes 0 ·
AgaveJoe avatar image
1 Vote"
AgaveJoe answered MarkusFreitag-0088 commented

What is the best way to debug this?

In visual Studio right click on the solution file and select properties. From there you can select multiple startup projects. I usually select "Current selection". Then click the web api project and press ctrl-F5 to start web api without the debugger. Next select the client app and run.

for debugging the web api app I'll click run then use PostMan to make the request. Frankly, you have a lot of posts and should take time to learn how to use Visual Studio.

How can I get this to run mode on another PC?

I'm not sure what "run mode" is or what you're asking. Just copy the entire solution to another PC and open the solution in Visual Studio.

If you are asking how to deploy the web api which is another Visual Studio question. Right click the Web API project, select publsihed, to a folder, enter the path, click finish. I used the path C:\inetpub\wwwroot\WebApiBasic. You'll surly have to create the WebApiBasic folder. finally publish the Web APi project. From here you can copy the deployed web api to another computer if needed.

C:\inetpub\wwwroot\ is the local IIS instance if you have IIS installed. Open InetMgr.exe to configure the web application. You'll find WebApiBasic under the "Default Web Site". Right click WebApiBasic and select "Convert to Application" - > ok. Under Manage application on the right click browse to open the Web API in a browser.

If you can still show the authorization, it would be great!

Once the you have Web API deployed to IIS you can configure basic authentication in IIS under the authentication feature. Note: you must create a user account on the machine. You can figure this out on your own.

Is there anything else you can say?

I'm not sure what you are asking.

I call then like this, right?

I added Get(id), Post, Put and Delete methods to the project.

I think it is import to point out that any beginning level Web API tutorial covers this stuff. Secondly, your customer must provide information on how the their service works. It is practically impossible build a client without the service documentation. You've mentioned that your customer does not supply this information which a very strange if they are actually your customer and paying you for development.

· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Many thanks for your help. Looks really good!

213790-you-are-the-best.png


213789--a.png
I have a PC, there is no VS2019 development available.
I want to install my application Desktop (WinForms), plus the WebApi to test if everything works.

If it works, great.
Then it goes to the customer, I switch the IP and test against the right system. This is my approach.

What is unclear is how I get the WebApi to run IIS enable, what exactly to select and where do the files need to be located?
Do you have a tip there.
That would be it for this thread, should there be anything else, I would open a new one. This one is quite long.


THANKS!


 ResponseOrder data2 = GetData2("2022-06-10-O425").GetAwaiter().GetResult(); 

Can you say something else about it, I don't know (GetAwaiter) this. That is asynchronous and I use that in a local function with void, right?

The last item
213850-possible-to-show-as-json-010.png

Is it possible to show it as JSON?

I use IInetMgr.exe and then localhost and port not visible..., why?
213856--not-hostname-and-port.png [2]: /answers/storage/attachments/213789--a.png


0 Votes 0 ·
AgaveJoe avatar image AgaveJoe MarkusFreitag-0088 ·

What is unclear is how I get the WebApi to run IIS enable, what exactly to select and where do the files need to be located?

I'm not sure what you're asking. The screenshots indicate the you have the WebApiBasic application properly configured in IIS. If you are trying to move the application to another machine then simply copy the WebApiBasic folder to the next machine.

Is it possible to show it as JSON?

An XML response is the default behavior with the Web API template in .NET Framework. Web API uses content negotiation and will return JSON if the client sends an Accept: application/json header. Use PostMan to test rather than the browser. PostMan provides better control over the request.

Can you say something else about it, I don't know (GetAwaiter) this.

The .NET Framework Console does not allow the Main entry point to be async. The GetAwaiter() allows the call to the async method to execute asynchronously from Main(). See the reference documentation for details.

Task.GetAwaiter Method

I use IInetMgr.exe and then localhost and port not visible..., why?

Port 80 (http) and 443 (https) are assumed in web applications.





1 Vote 1 ·

Thanks again!

http://localhost/WebApiBasic from InetMgr.exe

client.BaseAddress = new Uri("https://localhost:44328"); from Code
Where can I set the port to have the same call, the same address?
214183--question-1.png




The .NET Framework Console does not allow the Main entry point to be async.

I mostly have a desktop application WPF or WinForms. Then I can do it exactly the same way?

Or would you call the queries differently? I have always done it this way.



using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(CfgSystem.Baseaddress);
client.Timeout = new TimeSpan(0, 0, CfgSystem.Timeout);

string authorization = $"{CfgSystem.Username}:{CfgSystem.Password}";
Trace.Writeline($"RequestNewOrder, authorization='{authorization}'");

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(authorization)));
urlParameters = CfgSystem.UrlGetOrderData.Replace("{orderId}", orderId);

response = client.GetAsync(urlParameters).Result;


0 Votes 0 ·
-question-1.png (89.9 KiB)
Show more comments