简体   繁体   中英

Restful Web Service using C#

I have been assigned to come up with a web service that receives and posts data. However, I am very new to this, and even after looking up multiple examples and trying to follow them, I have a bit of a difficult time understanding.

Referenced examples:

Link 1

Link 2

The code that I have been given as a reference for the model and controller are the following:

Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Webservice.Models.ApiModels {
    public class SecondlyReading {
        [Key]
        public int Id { get; set; }
        [Required]
        public int Name { get; set; }
        [Required]
        public string TimeStamp { get; set; }
        [Required]
        public string Date { get; set; }
        [Required]

    }
}

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using SmartDBWeb.Data;
using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SmartDBWeb.Models.ApiModels;
using Microsoft.EntityFrameworkCore;


namespace Webservice.Controllers.Api {
    [Route("api/[controller]")]
    [Authorize]
    public class WebserviceController : Controller {
        private ApplicationDbContext _context;


        public WebserviceController(ApplicationDbContext context) {
            _context = context;
        }

        // GET: api/Webservice
        [HttpGet]
        public IEnumerable<Webservice> GetSecondlyReadings() {
            return _context.Webservice.ToList();
        }

        // GET api/Webservice/id
        [HttpGet("{id}")]
        public async Task<IActionResult> GetWebservice(int id) {
            var reading = await _context.Webservice.SingleOrDefaultAsync(c => c.Id == id);
            if (reading == null) {
                return NotFound();
            }

            return Ok(reading);
        }

        [HttpPost]
        public IActionResult PostWebservice([FromBody]List<Webservice> Readings) {
            if (!ModelState.IsValid) {
                return BadRequest();
            }
            foreach (Webservice reading in Readings) {
                _context.Webservice.Add(reading);
            }

            _context.SaveChanges();
            return CreatedAtAction("GetWebservice", new { id = Readings[0].Id }, Readings[0]);
        }
    }
}

My main question is how the use of the above code works in general. What I have found out(might not be correct), is that the the model is the data itself and the controller links the model and view together.

Start with asking yourself how Web Communication generally works. When accessing any website via your browser by typing in an address, what actually happens behind the scenes?

What I found to be very helpful was to open up a new tab in my browser and use Developer Tools (eg by right clicking anywhere and then clicking on "Inspect") to observe traffic by switching to the network tab. Access a website of your choice, say: wikipedia.org.

Now a bunch of stuff is going on, but you are interested in the first new entry to your network communication list that should say "www.wikipedia.org". Click on that.

You should now be looking at the "Headers" tab, specifically the request headers. There are two important fields:

  • Request URL : This tells the server what you want from it. It is a Resource locator, meaning that you want to access a resource from the server, say, a piece of HTML, an image or raw JSON data that you use in your application.
  • Request Method : This tells the server what you want to do with the resource you are trying to access. Do you want to GET it? Or do you want to PUT some resource on the server? Maybe you want to DELETE it or POST changes to this resource.

Let's go back to your source code.

What you provided above are a Model class and a Controller class.

Your model is a data structure that represents a resource within your web application. Id, Name, Timestamp, Date are attributes of this resource. Depending on your actual use case, you want to create, use, update or delete objects of this model type and decide on their attribute's values.

To allow your clients to do so, you have a controller class. It is the entry point for all web requests that "map" to :

[Route("api/[controller]")]

Map means, when the request URL of your client (remember our example "www.wikipedia.org") matches to the string you defined in your Route, this controller class is used (notice: [controller] will be replaced with the actual name of your controller class, in this case "Webservice".

Within your controller you define Actions . Depending on the Request URL and the Request Method (see above) of your client's request, your web framework decides, which action is called.

[HttpGet]

This maps to a GET request to the URL api/Webservice . The action's return type is a List, which means that multiple objects should be returned. In your case, when the client accesses api/Webservice , all objects within your _context.Webservice are returned.

[HttpGet("{id}")]

This maps to a GET request as well, but this time it requires a so called Query Parameter . This is an additional piece of information that your client provides to make its request more specific. Eg, they could be requesting api/Webservice?id=1 which would ask you to return the object with an id of 1.

[HttpPost]

This maps to a POST request and asks you to insert or update an object. [FromBody] tells the request processor to convert the so-called Request Body into an object of a given type. The request body is where your client will put entire objects - converted eg in JSON format - they want to submit to the server.

Now, I hope this makes your code examples a bit clearer to you. You also mentioned the View , so I will quickly explain what that is: Typically, after a request to your server, you respond with some sort of answer. In the most simple case, it is the Response Status that tells the client if everything went smooth. For a GET request, you typically return an object in the Response Body . What you return is called the view. In your example:

return Ok(reading);

converts the object that was retrieved from the database into a machine-readable format (eg JSON) and adds the response status "200 OK" to it. This is sent to your client.

So this should give you a good overview on how web frameworks work. I hope I could help you with this rather long read. Let me know if I can clarify anything.

Model: It is basically a table structure for the database. So, whenever you will create an object and set the values and insert the object in the database. Controller: It is used to deal with the HTTP calls and to link your business logic with the View.

[HttpGet]

This maps to a GET request to the URL api/Webservice without any query parameter. The actions return type is a List, which means that multiple objects should be returned. In your case, when the client accesses api/Webservice, all objects within your _context.Webservice are returned.

[HttpGet("{id}")]

This maps to a GET request as well, but this time it requires a so called Query Parameter. This is an additional piece of information that your client provides to make its request more specific. Eg, they could be requesting api/Webservice?id=1 which would ask you to return the object with an id of 1.

[HttpPost]

This maps to a POST request and asks you to insert or update an object. [FromBody] tells the request processor to convert the so-called Request Body into an object of a given type. The request body is where your client will put entire objects - converted eg in JSON format - they want to submit to the server. So, for the model

public class SecondlyReading {
        [Key]
        public int Id { get; set; }
        [Required]
        public int Name { get; set; }
        [Required]
        public string TimeStamp { get; set; }
        [Required]
        public string Date { get; set; }
    }

This will create a datatable with Id as the primary key because you are using [Key] attribute.

private ApplicationDbContext _context;

This is used to create a database context. You might have also created the following in ApplicationDbContext class

public DbSet<SecondlyReading> WebService{get; set;}

It will create a DbSet with name WebService.

In WEB APIs, POST is used to insert new data. So, here the API api/webservice in POST, will be used to insert the data. You can insert the data using any CLIENT like POSTMAN or ARC. You have to set the data in body of request of the HTTP call. The response of the API can be JSON or XML depending on your output.

我认为最好阅读基础知识,这样您才能了解Web API的正常工作方式以进行自读https://www.asp.net/web-api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM