vue +asp.net core webapi跨域

发布时间 2023-10-18 21:44:27作者: .net&new

 

 

 

 

 

 

 

 

 

 

vue代码:

 

 

login.vue 

 

<template>
    <div class="login-wrap">
       
    <el-button type="primary" style="width:100%;" @click="doSubmit()">提交</el-button>
       
    </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Login',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
   
  },
  methods:{
    doSubmit: function()
    {
        axios.get('/api/WeatherForecast/get').then(
            response => {
                console.log('请求成功了')
                //请求成功后更新List的数据
                console.log("返回值:"+response.data);

               
            },
            error => {
                //请求后更新List的数据
                alert('菜鸡,你失败了');

                console.log("失败返回值:"+error);

            }
        )

   },
   gotoRegister: function(){
   
   console.log("注册信息")
}
}
}
</script>

<style scoped>
   
</style>
 
 
vue.config.js代码
 
 
module.exports = {
  devServer:{
    proxy:{
      '/api':{//表示拦截以/api开头的请求路径
        target:'http://localhost:5232',
        changOrigin: true,//是否开启跨域
        pathRewrite:{
          '^/api':'' //重写api,把api变成空字符,因为我们真正请求的路径是没有api的
        }
      }
    }
  }
}
 
 
webapi代码
 
 

using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Text;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace WebApplication2.Controllers
{
[ApiController]
[Route("api/[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}

[HttpPost]
public string Login([FromBody] UserModel userModel)
//public string Login(string userName, string password)
{
//var Permission = "Permission";
var userId = "1";
//验证用户名密码
//创建JWT
// header
var signingAlgorithm = SecurityAlgorithms.HmacSha256;
// payload
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub,userId),
};
var secretByte = Encoding.UTF8.GetBytes("dengfenglaiSecretKey");

var signingKey = new SymmetricSecurityKey(secretByte);
var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);

var token = new JwtSecurityToken(
//颁发者
issuer: "dengfneglai", //_configuration["Authentication:Issuer"],
//接收者
audience: "zhuifengqu", //_configuration["Authentication:Audience"],
//自定义参数
claims,
notBefore: DateTime.UtcNow,
//过期时间
expires: DateTime.UtcNow.AddDays(1),
//签名证书
signingCredentials
);
var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
return tokenStr;

//return "哈哈哈";

}

[Serializable]
public class UserModel
{
public string username { get; set; }
public string password { get; set; }

}


public class JWTTokenOptions
{
public string Audience { get; set; }
public string SecurityKey { get; set; }
public string Issuer { get; set; }
}

 

 

}

public interface ICustomJWTService
{
string GetToken(string UserName, string PassWord);
}
}

 

 

Program.cs代码

 

 

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddCors(options =>
options.AddPolicy("cors",
p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()));
var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseAuthorization();

app.MapControllers();

app.Run();