Net Core 学习入门(七)----------API+Swagger+(重写路由)

1,新建一个web应用程序,选择API.

2,使用nuget导入swagger,swagger是一个为api接口生成在线xml第三方插件。

选择  Swashbuckle.AspNetCore这个包。

3,配置

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;

namespace API
{
    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.AddMvc();
            services.AddSwaggerGen(options => {

                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version = "v1",
                    Title = " API 文档",
                    Description = "by bj eland"
                });
            });
          

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
             
            });
          
        }
    }
}

4,选择项目右键属性-生成,勾选为这个项目生成xml文件。


5,配置登录为swagger

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:55191/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "launchUrl": "swagger",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    },
    "API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:55192/"
    }
  }
}

6 ,运行,oK

7,添加一个demo方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        /// 
        ///测试
        /// 
        /// 
        [HttpGet]
        public IEnumerable Demo ()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values
        [HttpGet]
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

再次运行,发现不能正确的生成文档了,原因在路由映射身上,

我们修改路由映射为[Route("api/[controller]/[action]")],加了一层action,运行ok.

      因为之前路由到controller,api是根据浏览器的动作执行不同的方法,比如get不带参数执行get方法,get带参数动作执行get(id)方法,那么我们加了一个demo标记为httpget方法之后,api根据路由规则就匹配到两个get方法,那么api就不能在为get动作精准的匹配一个方法了,api犯了选择困难症呀。解决的方式就是再加一层映射,让api根据浏览器传递的具体action名字去匹配,这样以来即使存在俩个无参数的get方法,那么方法名不一样,我们的api也能根据路由正确找到执行的方法了。

8,当然每次建立一个controller去配置路由,我这种懒人是觉得十分麻烦的,能不能只配置一次呢。

    我们建立了一个BaseController:Controller,然后在这个类上修改路由。

     以后我们新建的Controller统一继承BaseController,这样就不用在重新修改路由了。






你可能感兴趣的:(netcore学习)