.Net Core 3.1 Web API基础知识

在Startup类的ConfigureServices方法内添加以下注入代码:
复制代码
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(“v1”, new OpenApiInfo
{
Title = “My API”,
Version = “v1”,
Description = “API文档描述”,
Contact = new OpenApiContact
{
Email = “5007032@qq.com”,
Name = “测试项目”,
//Url = new Uri(“http://t.abc.com/”)
},
License = new OpenApiLicense
{
Name = “BROOKE许可证”,
//Url = new Uri(“http://t.abc.com/”)
}
});

        });

复制代码
Startup类的Configure方法添加如下代码:

复制代码
//配置Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", “My API V1”);
c.RoutePrefix = “api”;// 如果设为空,访问路径就是根域名/index.html,设置为空,表示直接在根域名访问;想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = “swagger”; 则访问路径为 根域名/swagger/index.html

        });

复制代码
然而到这里还没完,相关接口的注释说明我们看不到,通过配置XML文件的方式继续调整代码如下,新增代码见加粗部分:
复制代码
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(“v1”, new OpenApiInfo
{
Title = “My API”,
Version = “v1”,
Description = “API文档描述”,
Contact = new OpenApiContact
{
Email = “5007032@qq.com”,
Name = “测试项目”,
//Url = new Uri(“http://t.abc.com/”)
},
License = new OpenApiLicense
{
Name = “BROOKE许可证”,
//Url = new Uri(“http://t.abc.com/”)
}
});

            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(xmlPath);
        });

调整系统默认输出路径
项目启动后,默认会访问自带的weatherforecast,如果想调整为其他路径,譬如打开后直接访问Swagger文档,那么调整Properties目录下的launchSettings.json文件,修改launchUrl值为api(前述配置的RoutePrefix值):
复制代码
{
“$schema”: “http://json.schemastore.org/launchsettings.json”,
“iisSettings”: {
“windowsAuthentication”: false,
“anonymousAuthentication”: true,
“iisExpress”: {
“applicationUrl”: “http://localhost:7864”,
“sslPort”: 0
}
},
“profiles”: {
“IIS Express”: {
“commandName”: “IISExpress”,
“launchBrowser”: true,
“launchUrl”: “api”,
“environmentVariables”: {
“ASPNETCORE_ENVIRONMENT”: “Development”
}
},
“CoreApi_Demo”: {
“commandName”: “Project”,
“launchBrowser”: true,
“launchUrl”: “api”,
“applicationUrl”: “http://localhost:5000”,
“environmentVariables”: {
“ASPNETCORE_ENVIRONMENT”: “Development”
}
}
}
}
复制代码

回到顶部
三、配置文件
以读取appsettings.json文件为例,当然你也定义其他名称的.json文件进行读取,读取方式一致,该文件类似于Web.config文件。为方便示例,定义appsettings.json文件内容如下:

复制代码
{
“ConnString”: “Data Source=(local);Initial Catalog=Demo;Persist Security Info=True;User ID=DemoUser;Password=123456;MultipleActiveResultSets=True;”,
“ConnectionStrings”: {
“MySQLConnection”: “server=127.0.0.1;database=mydemo;uid=root;pwd=123456;charset=utf8;SslMode=None;”
},
“SystemConfig”: {
“UploadFile”: “/Files”,
“Domain”: “http://localhost:7864”
},
“JwtTokenConfig”: {
“Secret”: “fcbfc8df1ee52ba127ab”,
“Issuer”: “abc.com”,
“Audience”: “Brooke.WebApi”,
“AccessExpiration”: 30,
“RefreshExpiration”: 60
},
“Logging”: {
“LogLevel”: {
“Default”: “Information”,
“Microsoft”: “Warning”,
“Microsoft.Hosting.Lifetime”: “Information”
}
},
“AllowedHosts”: “*”
}
复制代码

1、配置文件的基本读取
复制代码
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        //读取方式一
        var ConnString = Configuration["ConnString"];            
        var MySQLConnection = Configuration.GetSection("ConnectionStrings")["MySQLConnection"];
        var UploadPath = Configuration.GetSection("SystemConfig")["UploadPath"];
        var LogDefault = Configuration.GetSection("Logging").GetSection("LogLevel")["Default"];
        
        //读取方式二
        var ConnString2 = Configuration["ConnString"];
        var MySQLConnection2 = Configuration["ConnectionStrings:MySQLConnection"];
        var UploadPath2 = Configuration["SystemConfig:UploadPath"];
        var LogDefault2 = Configuration["Logging:LogLevel:Default"];
        
    }    
    
}

复制代码
以上介绍了2种读取配置信息的方式,如果要在Controller内使用,类似地,进行注入并调用如下:

复制代码
public class ValuesController : ControllerBase
{
private IConfiguration _configuration;

    public ValuesController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        var ConnString = _configuration["ConnString"];
        var MySQLConnection = _configuration.GetSection("ConnectionStrings")["MySQLConnection"];
        var UploadPath = _configuration.GetSection("SystemConfig")["UploadPath"];
        var LogDefault = _configuration.GetSection("Logging").GetSection("LogLevel")["Default"];
        return new string[] { "value1", "value2" };
    }
}

复制代码

2、读取配置文件到自定义对象
以SystemConfig节点为例,定义类如下:

复制代码
public class SystemConfig
{
public string UploadPath { get; set; }
public string Domain { get; set; }

}

复制代码
调整代码如下:

复制代码
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.Configure<SystemConfig>(Configuration.GetSection("SystemConfig"));
    }    
    
}

复制代码
然后Controller内进行注入调用:

复制代码
[Route(“api/[controller]/[action]”)]
[ApiController]
public class ValuesController : ControllerBase
{
private SystemConfig _sysConfig;
public ValuesController(IOptions sysConfig)
{
_sysConfig = sysConfig.Value;
}

    [HttpGet]
    public IEnumerable<string> GetSetting()
    {
        var UploadPath = _sysConfig.UploadPath;
        var Domain = _sysConfig.Domain;
        return new string[] { "value1", "value2" };
    }
}

复制代码
3、绑定到静态类方式读取
定义相关静态类如下:

public static class MySettings
{
public static SystemConfig Setting { get; set; } = new SystemConfig();
}
调整Startup类构造函数如下:

复制代码
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”, optional: true, reloadOnChange: true);

        Configuration = builder.Build();
        //Configuration = configuration;

        configuration.GetSection("SystemConfig").Bind(MySettings.Setting);//绑定静态配置类           
    }       

复制代码
接下来,诸如直接使用:MySettings.Setting.UploadPath 即可调用。

回到顶部
四、文件上传
接口一般少不了文件上传,相比.net framework框架下webapi通过byte数组对象等复杂方式进行文件上传,.Net Core WebApi有了很大变化,其定义了新的IFormFile对象来接收上传文件,直接上Controller代码:

后端代码
复制代码
[Route(“api/[controller]/[action]”)]
[ApiController]
public class UploadController : ControllerBase
{
private readonly IWebHostEnvironment _env;

    public UploadController(IWebHostEnvironment env)
    {
        _env = env;
    }

    public ApiResult UploadFile(List<IFormFile> files)
    {
        ApiResult result = new ApiResult();

//注:参数files对象去也可以通过换成: var files = Request.Form.Files;来获取

        if (files.Count <= 0)
        {
            result.Message = "上传文件不能为空";
            return result;
        }

        #region 上传          

        List<string> filenames = new List<string>();

        var webRootPath = _env.WebRootPath;
        var rootFolder = MySettings.Setting.UploadPath;           

        var physicalPath = $"{webRootPath}/{rootFolder}/";

        if (!Directory.Exists(physicalPath))
        {
            Directory.CreateDirectory(physicalPath);
        }

        foreach (var file in files)
        {
            var fileExtension = Path.GetExtension(file.FileName);//获取文件格式,拓展名               

            var saveName = $"{rootFolder}/{Path.GetRandomFileName()}{fileExtension}";
            filenames.Add(saveName);//相对路径

            var fileName = webRootPath + saveName;

            using FileStream fs = System.IO.File.Create(fileName);
            file.CopyTo(fs);
            fs.Flush();

        }          
        #endregion


        result.IsSuccess = true;
        result.Data["files"] = filenames;

        return result;
    }
}

复制代码
前端调用
接下来通过前端调用上述上传接口,在项目根目录新建wwwroot目录(.net core webapi内置目录 ),添加相关js文件包,然后新建一个index.html文件,内容如下:

复制代码







<script type="text/javascript">

    $(function () {

    });

</script>
复制代码 上述通过构建FormData和ajaxSubmit两种方式进行上传,需要注意的是contentType和processData两个参数的设置;另外允许一次上传多个文件,需设置multipart属性。

在访问wwwroot下的静态文件之前,必须先在Startup类的Configure方法下进行注册:

public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();//用于访问wwwroot下的文件
}
龙华大道1号 http://www.kinghill.cn/Dynamics/2106.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值