ASP.NET Core Web API + Vue

一、创建ASP.NET Core Web API 程序

ASP.NET Core Web API + Vue_第1张图片

二、添加API控制器

 ASP.NET Core Web API + Vue_第2张图片

创建一个叫Product的api控制器 

例:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using apiCore.Models;
namespace apiCore.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        public IEnumerable Get() {
            return new List { new Product {ProductID=1,ProductName="苹果手机",ProductPrice=4999 },
                new Product {ProductID=2,ProductName="苹果手机",ProductPrice=4999 }

            };
        }
    }
}

三、配置Startup.cs文件

一、ConfigureServices()方法

(1)声明跨域策略名称

(2)添加跨域服务

(3)声明跨域策略:允许所有域、任何请求标头和全部http方法

二、Configure()方法

(1)使用允许跨域请求

(2)所有请求都应用跨域请求策略

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

namespace apiCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        //声明跨域策略名称
        readonly string MyCorsPolicy = "CorsPolicy";
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //添加跨域服务
            services.AddCors(options =>
            {
                //声明跨域策略:允许所有域、任何请求标头和全部http方法
                options.AddPolicy(MyCorsPolicy,builder=> { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); });
            });
            services.AddControllers();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseRouting();
            //使用允许跨域请求
            app.UseCors();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                //所有请求都应用跨域请求策略
                endpoints.MapControllers().RequireCors(MyCorsPolicy);
            });
        }
    }
}

四、前端页面进行交互

(1)引用vue.js、axios.js文件

(2)在axios.get()方法里写你创建的api控制器的地址 例如:'http://localhost:40657/api/values'



	
		
		
		
		
	
	
		
{{item.productID}} {{item.productName}} {{item.productPrice}}

你可能感兴趣的:(前端,asp.net,javascript)