C# webAPI detailed explanation

Getting startedCreating a web project

First create a web project that can basically run and use postman to test the interface. Both
.NET Framework and .NET Core can create webAPI. It is easier to use .NET Framework here.
Start Visual Studio and select New Project from the Start page. Alternatively, on the File menu, select New, then select Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the project template list, select ASP.NET Web Application or search for "ASP.NET Web Application" directly on the creation page

Select webAPI
Insert image description here

After creating it, close the overview page first.
The only folders you need to pay attention to next are models and Controllers. Add the Product class
in models.

namespace ProductsApp.Models
{
    
    
    public class Product
    {
    
    
        public int Id {
    
     get; set; }
        public string Name {
    
     get; set; }
        public string Category {
    
     get; set; }
        public decimal Price {
    
     get; set; }
    }
}

Add the controller webapi 2 in controllers. If you
Insert image description here
fill in the name, be sure to add the name of the corresponding data class before the controller - ProductsController.

Getting Started Definition Method

Define GetAllProducts() and GetProduct() methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using WebApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    
    
    public class ProductsController : ApiController
    {
    
    
        Product[] products = new Product[]
        {
    
    
            new Product {
    
     Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product {
    
     Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product {
    
     Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };

        public IEnumerable<Product> GetAllProducts()
        {
    
    
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
    
    
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
    
    
                return NotFound();
            }
            return Ok(product);
        }
    }
}

Next, you can see our api by running it directly.

Insert image description here

If an error is reported and localhost rejects our connection request, it is most likely that the port is busy. Wait a moment and it will be normal.

Enter https://localhost:44378/api/Products to view the returned results.
At this point, the web api is simply completed.

Return result of entry operation

How ASP.NET Web API converts return values ​​from controller actions into HTTP response messages
.
Insert image description here
If the operation returns an HttpResponseMessage, Web API uses the properties of the HttpResponseMessage object to populate the response, converting the return value directly into an HTTP response message.

public class ValuesController : ApiController
{
    
    
    public HttpResponseMessage Get()
    {
    
    
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("hello", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
    
    
            MaxAge = TimeSpan.FromMinutes(20)
        };
        return response;
    } 
}

IHttpActionResult can be implemented using the IHttpActionResult defined in the System.Web.Http.Results namespace in actual use. The ApiController class defines helper methods that return the results of these built-in operations.

It defines many return types that can be called directly

public IHttpActionResult Get (int id)
{
    
    
    Product product = _repository.Get (id);
    if (product == null)
    {
    
    
        return NotFound(); // Returns a NotFoundResult
    }
    return Ok(product);  // Returns an OkNegotiatedContentResult
}

Getting started help pages and documentation

Add API documentation

By default, help pages contain placeholder strings for documentation. Documents can be created using XML document comments. To enable this feature, open the file Areas/HelpPage/App_Start/HelpPageConfig.cs and uncomment the following lines

config.SetDocumentationProvider(new XmlDocumentationProvider(
    HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

Check the next step and enter the generation path.
Insert image description here
When completed, write /// to the method on the controller ///Comments will be displayed on the help document


        /// <summary>
        /// 方法名和请求方式是一一对应的
        /// </summary>
      public IHttpActionResult GetEmployee(int id)

Insert image description here

routing

Guess you like

Origin blog.csdn.net/qq_43886548/article/details/130966157
Recommended