.Net Core WebAPI 搭建

1.创建项目

使用开发工具为 Visual Studio 2017

2.创建 Controller

实体类

    public class Book
    {
        public string ID { get; set; }
        public string Name { get; set; }
    }

Controller

   [Produces("application/json")]
   [Route("api/Book")]
   public class BookController : Controller

   {
       static List<Book> list = new List<Book>() {
           new  Book(){  ID="1", Name="Book1"},
           new  Book(){  ID="2", Name="Book2"},
           new  Book(){  ID="3", Name="Book3"},
       };
       // GET: api/Book
       [HttpGet]
       public List<Book> Get()
       {
           return list;
       }

       // GET: api/Book/5
       [HttpGet("{id}", Name = "Get")]
       public Book Get(int id)
       {
           return list.Single(t => t.ID == id.ToString());
       }
       
       // POST: api/Book
       [HttpPost]
       public void Post(Book value)
       {
           list.Add(value);
       }
   }

3.发布为可执行文件

4.直链访问图片

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();

        app.UseFileServer(new FileServerOptions()
        {
            FileProvider = new PhysicalFileProvider(
            AppContext.BaseDirectory +"\\Image"), //实际目录地址
            RequestPath = new Microsoft.AspNetCore.Http.PathString("/Image"), //用户访问地址
            EnableDirectoryBrowsing = true //开启目录浏览
        });
    }

问题解决:

1.Post方法提示 415

将参数前的 [FromBody] 删除

2.Json数据所有属性全部为小写

修改 Startup.cs 类中的

        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc();

            services.AddMvc().AddJsonOptions(
                t => t.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
        }

3.查找到重复引用

解决: 创建 Controller 是创建空的Controller,自己在一个个写方法。

Last modification:January 14th, 2020 at 07:33 pm