• asp.net core 2.1 WebApi 快速入门


    参考:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.1

    官网的例子

    直接去看,这里写用到的代码

    创建一个model

    namespace TodoApi.Models
    {
        public class TodoItem
        {
            public long Id { get; set; }
            public string Name { get; set; }
            public bool IsComplete { get; set; }
        }
    }
    

    创建数据库上下文

    using Microsoft.EntityFrameworkCore;
    
    namespace TodoApi.Models
    {
        public class TodoContext : DbContext
        {
            public TodoContext(DbContextOptions<TodoContext> options)
                : base(options)
            {
            }
    
            public DbSet<TodoItem> TodoItems { get; set; }
        }
    }
    

    Register the database context

     public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<TodoContext>(opt =>
                                opt.UseInMemoryDatabase("TodoList"));
    							
                services.AddMvc()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
    

    添加控制器 TodoController

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Cors;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using TodoApi.Models;
    
    namespace TodoApi.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        [EnableCors("any")]
        public class TodoController : ControllerBase
        {
            private readonly TodoContext _context;
    
            public TodoController(TodoContext context)
            {
                _context = context;
    
                if (_context.TodoItems.Count() == 0)
                {
                    // Create a new TodoItem if collection is empty,
                    // which means you can't delete all TodoItems.
                    _context.TodoItems.Add(new TodoItem { Name = "Item1" });
                    _context.SaveChanges();
                }
            }
    
    
            // GET api/todo
            [HttpGet]
            public ActionResult<List<TodoItem>> GetAll()
            {
                return _context.TodoItems.ToList();
            }
    
    
            // GET api/todo/{id}
            [HttpGet("{id}", Name = "GetTodo")]
            public ActionResult<TodoItem> GetById(long id)
            {
                var item = _context.TodoItems.Find(id);
                if (item == null)
                {
                    return NotFound();
                }
                return item;
            }
    
    
            //POST /api/todo/  
            //Postman: Body->Raw->Json-> {"name":"Item2~","isComplete":false}
            //Header:  Location →http://localhost:64425/api/Todo/2
            [HttpPost]
            public ActionResult Create(TodoItem item)
            {
                _context.TodoItems.Add(item);
                _context.SaveChanges();
    
                return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
            }
    
    
    
            [HttpPut("{id}")]
            public ActionResult Update(long id, TodoItem item)
            {
                var todo = _context.TodoItems.Find(id);
                if (todo == null)
                {
                    return NotFound();
                }
    
                todo.IsComplete = item.IsComplete;
                todo.Name = item.Name;
    
                _context.TodoItems.Update(todo);
                _context.SaveChanges();
                return NoContent();
            }
    
            [HttpDelete("{id}")]
            public IActionResult Delete(long id)
            {
                var todo = _context.TodoItems.Find(id);
                if (todo == null)
                {
                    return NotFound();
                }
    
                _context.TodoItems.Remove(todo);
                _context.SaveChanges();
                return NoContent();
            }
        }
    }
    

    然后可以调用了。上面代码已经设置跨域 Microsoft.AspNetCore.Cors;

    跨域

    1.全局配置中启用跨域处理,命名为‘any’,任何都可以访问

    public void ConfigureServices(IServiceCollection services)
    {
        //配置跨域处理
        services.AddCors(options =>
        {
            options.AddPolicy("any", builder =>
            {
                builder.AllowAnyOrigin() //允许任何来源的主机访问
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();//指定处理cookie
            });
        });
    }
    

    2.在控制器或Action的方法注释上使用对应名称的 跨域规则,
    [EnableCors("any")]

        [Produces("application/json")]
        [Route("api/Menu")]
        [EnableCors("any")] //设置跨域处理的 代理
        public class MenuController : Controller
        {
        }
    

    1.后台通过HttpContext上下文可以直接操作Cookie
    2.前台JQuery的ajax请求,需要携带withCredentials才会将cookie的值保存到客户端

    跨域:https://www.cnblogs.com/tianma3798/p/6920704.html

  • 相关阅读:
    快速排序学习
    转载 libSVM介绍(二)
    支持向量机: Maximum Margin Classifier
    联发科笔试题之字符编码
    研究1
    在OnLButtonDown获取其他控件被点击的消息
    希尔排序学习
    快速排序
    别人的string的实现,有时间好好学习下
    完成动态根据类别动态填充区域颜色
  • 原文地址:https://www.cnblogs.com/tangge/p/10073378.html
Copyright © 2020-2023  润新知