sportdog

导航

 

问题:

  在.Net Core 中创建的WebApi如何进行测试。

解决:

  使用第三方控件Swagger

遇到的问题:

  1.   测试页面无法显示出来:后发现在火狐、IE下无法显示,换成Chrome就可以了。
  2.   在测试页面执行WebApi Action时,提示404网页无法找到的错误:尝试直接运行Action ,显示网页不存在。后发现在删除Startup.cs里部分代码造成的。

配置过程

1:创建一个空的.Net Core WebApi 项目,项目里自带(WeatherForecastController)

2:项目添加倚赖项,在Nuget里直接安装,见下图:

3:修改StartUp.cs文件,代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.HttpsPolicy;
 8 using Microsoft.AspNetCore.Mvc;
 9 using Microsoft.Extensions.Configuration;
10 using Microsoft.Extensions.DependencyInjection;
11 using Microsoft.Extensions.Hosting;
12 using Microsoft.Extensions.Logging;
13 
14 
15 using Swashbuckle.AspNetCore.Swagger;
16 using Microsoft.OpenApi.Models;
17 
18 namespace WebApi
19 {
20     public class Startup
21     {
22         public Startup(IConfiguration configuration)
23         {
24             Configuration = configuration;
25         }
26 
27         public IConfiguration Configuration { get; }
28 
29         // This method gets called by the runtime. Use this method to add services to the container.
30         [Obsolete]
31         public void ConfigureServices(IServiceCollection services)
32         { 
33             services.AddControllers();
34 
35             // 注册Swagger服务
36             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
37             services.AddSwaggerGen(c =>
38             {
39                 c.SwaggerDoc("v1.0", new OpenApiInfo { Title = "My Demo API", Version = "1.0" });
40                 //c.IncludeXmlComments(System.IO.Path.Combine(System.AppContext.BaseDirectory, "ZhiKeCore.API.xml"));
41             });
42 
43         }
44 
45 
46        
47         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
48         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
49         {
50             if (env.IsDevelopment())
51             {
52                 app.UseDeveloperExceptionPage();
53             }
54 
55             app.UseHttpsRedirection();
56 
57             app.UseRouting();
58 
59             app.UseAuthorization();
60 
61             app.UseEndpoints(endpoints =>
62             {
63                 endpoints.MapControllers();
64             });
65 
66             app.UseSwagger();
67             app.UseSwaggerUI(c =>
68             {
69                 c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My Demo API (V 1.0)");
70             });
71         }
72     }
73 }
View Code

4:设置项目启动页(不设也行),运行后手动输入Url(Swagger)也可以。

运行程序:效果如下

在对User 下的Actiong 进行测试,见下图:

测试结果如下图:

 

posted on 2020-11-02 13:29  sportdog  阅读(368)  评论(0)    收藏  举报