.Net6 web API (保姆级别)

前沿

之前感觉学.net8太超前了,先学下.net6 吧 然后再学8,因为企业都是6.0 开始的

发现其实6和8 差不多,就是有些写法不一样

好了进入正题创建项目其实和8 差不多

都是 REST

REST全称是RepresentationalStateTransfer,中文意思是表述性状态转移
REST本身并没有创造新的技术、组件或服务
REST指的是一组架构约束条件和原则。
如果一个架构符合REST的约束条件和原则,我们就称它为RESTfu1架构。
理论上REST架构风格并不是绑定在HTTP上,只不过目前HTTP是唯一与REST相关的实例。所以我们这里描述的
REST也是通过HTTP实现的REST。

创建6-项目

按照这个方法进行

 输入你的项目名称

1.浏览器访问--只能是Get请求。
2.swagger访问I
3.后台模拟Http请求访问  HttpClient
4.CoreWebAPI返回结果中文乱码问题解决

 

然后再跟目录新建一个2个类

 

 下面分别是代码

namespace yanfanNet6WebApi;

public class User
{
    /// <summary>
    /// 用户ID
    /// </summary>
    public int Id { get; set; }
    /// <summary>
    /// 用户名称
    /// </summary>
    public string? Name { get; set; }
    /// <summary>
    /// 用户年龄
    /// </summary> 
    public int Age { get; set; }
}
namespace yanfanNet6WebApi;

public class Company
{
    /// <summary>
    /// 公司ID
    /// </summary>
    public int Id { get; set; }
    //public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    /// <summary>
    /// 公司名称
    /// </summary>
    public string? Name { get; set; }
    /// <summary>
    /// 公司地址
    /// </summary> 
    public string? AddRess { get; set; }
}

然后在你的控制器内新建2个

 

举例user

using Microsoft.AspNetCore.Mvc;
using yanfanNet6WebApi.Utility.Swagger;

namespace yanfanNet6WebApi.Controllers;

[ApiController]
[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
public class UserController : ControllerBase
{

    private readonly ILogger<UserController> _logger;

    public UserController(ILogger<UserController> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <returns></returns>
    [HttpGet(Name = "User")]
    public User GetUser()
    {
        return new()
        {
            Id = 234,
            Name = "Ric",
            Age = 18
        };
    }

    /// <summary>
    /// 新增用户信息
    /// </summary>
    /// <returns></returns>
    [HttpPost(Name = "User")]
    public int AddUser(User user)
    {
        return 1;
    }

    /// <summary>
    /// 修改用户信息
    /// </summary>
    /// <returns></returns>
    [HttpPut(Name = "User")]
    public int UpdateUser(User user)
    {
        return 1;
    }

    /// <summary>
    /// 删除用户信息
    /// </summary>
    /// <returns></returns>
    [HttpDelete(Name = "User")]
    public int DeleteUser(int userId)
    {
        return 1;
    }
}

这样 

swagger 乱码注释:

        // 解决中文乱码问题
        builder.Services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });

 swagger 注释 和版本:

需要概2处地方:

        builder.Services.AddSwaggerGen(option => {
            #region 版本配置
            typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
            {
                option.SwaggerDoc(version, new OpenApiInfo()
                {
                    Title = $"{version}:我的CoreWebApi~",
                    Version = version,
                    Description = $"coreWebApi版本{version}"
                });
            });
            #endregion
        });

  

  app.UseSwaggerUI(option => {
                foreach (string version in typeof(ApiVersions).GetEnumNames())
                {
                    option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"版本:{version}");
                }
            });

 别忘记在控制器内引入:

 这个方法,啊哈哈哈

然后再运行就可以看到版本了

 直接超神

swagger token 

还是一样的操作

            #region 支持token产值
            {
                option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "请输入token,格式为Bearer xxxxxxxx(注意中间必须有空格)",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
            }
            #endregion

 

swagger 特性路由

    /// <summary>
    /// 获取用户ID
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    //[Route("{userId}")]
    [Route("GetUserById/{userId:int}")]
    public User GetUserById(int userId)
    {
        return new()
        {
            Id = 234,
            Name = "Ric",
            Age = 18
        };
    }

想要获取制定的ID 来获取

   [Route("GetUserById/{userId:int}")]

给请求约束了只能是 int 整型 的请求

 

 这样就成功了。

 

封装AddSwaggerGen

 

using System;
using Microsoft.OpenApi.Models;

namespace yanfanNet6WebApi.Utility.Swagger
{
    /// <summary>
    /// 版本枚举
    /// </summary>
    public static class SwaggerExtension
    {
        /// <summary>
        /// 扩展方法
        /// </summary>
        /// <param name="builder"></param>
        public static void AddSwaggerGenExt(this WebApplicationBuilder builder)
        {
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(option => {
                #region 版本配置
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    option.SwaggerDoc(version, new OpenApiInfo()
                    {
                        Title = $"{version}:我的CoreWebApi~",
                        Version = version,
                        Description = $"coreWebApi版本{version}"
                    });
                });
                #endregion

                #region 支持token产值
                {
                    option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                    {
                        Description = "请输入token,格式为Bearer xxxxxxxx(注意中间必须有空格)",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,
                        BearerFormat = "JWT",
                        Scheme = "Bearer"
                    });
                }
                #endregion

                #region 文件按钮上传
                //{
                //    option.OperationFilter<IOperationFilter>();
                //}
                #endregion
            });
        }

        /// <summary>
        /// swagger 中间件配置应用
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwaggerExt(this WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(option => {
                foreach (string version in typeof(ApiVersions).GetEnumNames())
                {
                    option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"API版本:{version}");
                }
            });
        }
    }
}
View Code

 

把 Program.cs 文件给注释掉

        WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
        // var builder = WebApplication.CreateBuilder(args);

再改

 WebApplication app = builder.Build();
        //var app = builder.Build();
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models; // 就是注释引入
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using yanfanNet6WebApi.Utility.Swagger;

namespace yanfanNet6WebApi;

public class Program
{
    public static void Main(string[] args)
    {
        WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
        // var builder = WebApplication.CreateBuilder(args);

        // Add services to the container
        // 解决中文乱码问题
        builder.Services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

        //SwaggerExtension.AddSwaggerGenExt();
        builder.AddSwaggerGenExt();
        //builder.Services.AddEndpointsApiExplorer();
        //builder.Services.AddSwaggerGen(option => {
        //    #region 版本配置
        //    typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
        //    {
        //        option.SwaggerDoc(version, new OpenApiInfo()
        //        {
        //            Title = $"{version}:我的CoreWebApi~",
        //            Version = version,
        //            Description = $"coreWebApi版本{version}"
        //        });
        //    });
        //    #endregion

        //    #region 支持token产值
        //    {
        //        option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
        //        {
        //            Description = "请输入token,格式为Bearer xxxxxxxx(注意中间必须有空格)",
        //            Name = "Authorization",
        //            In = ParameterLocation.Header,
        //            Type = SecuritySchemeType.ApiKey,
        //            BearerFormat = "JWT",
        //            Scheme = "Bearer"
        //        });
        //    }
        //    #endregion

        //    #region 文件按钮上传
        //    //{
        //    //    option.OperationFilter<IOperationFilter>();
        //    //}
        //    #endregion
        //});


        WebApplication app = builder.Build();
        //var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            // 等于下面的代码
            //SwaggerExtension.UseSwaggerExt(app);
            app.UseSwaggerExt();

            //app.UseSwagger();
            //app.UseSwaggerUI(option => {
            //    foreach (string version in typeof(ApiVersions).GetEnumNames())
            //    {
            //        option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"API版本:{version}");
            //    }
            //});
        }

        app.UseAuthorization();


        app.MapControllers();

        app.Run();
    }
}
View Code

最后封装成这样 然后和运行 和之前的一模一样

 

posted @ 2024-05-15 16:14  -鹿-  阅读(237)  评论(0编辑  收藏  举报