ASP Net Web API由于使用axios和reactjs的CORS策略而阻止请求

snz8szmq  于 2023-05-22  发布在  React
关注(0)|答案(1)|浏览(86)

我的program.cs文件包含以下代码

using fac.MongoConn;
using fac.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Session;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Cors;

var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins, builder =>
    {
        builder.WithOrigins("http://localhost:3000")
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});

builder.Services.Configure<MongoDBSettings>(builder.Configuration.GetSection("MondoDB"));
builder.Services.AddSingleton<MongoDBService>();

builder.Services.AddHttpContextAccessor();

builder.Services.AddMemoryCache();
builder.Services.AddDistributedMemoryCache();


builder.Services.AddSession(options =>
{
    options.Cookie.Name = "Session";
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
    };
});

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseSession();
app.UseAuthorization();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.MapControllers();
app.Run();

我的test.cs控制器有以下代码

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace fac.Controllers
{
    [EnableCors("_myAllowSpecificOrigins")]
    [Route("api/[controller]")]
    [ApiController]
    public class test : ControllerBase
    {
        [HttpGet]
        public IActionResult Index()
        {
            return Ok("test");
        }
    }
}

我用react创建了一个简单的表单

import React,{useEffect, useState} from 'react'
import axios from 'axios';

const Login = () => {
    const [user,setUser] = useState({
        username: '',
        password: ''
    })
    const {username,password} = user;
    const chnageHandler = e => {
        setUser({...user,[e.target.name]:[e.target.value]})
    }
    // useEffect(() => {
        
    // });

    const loginUser = async () => {
        try {
            const response = await axios.get('http://localhost:5082/api/test');
            console.log(response);
        } catch (error) {
            console.log(error);
        }
    }

    const submitHandller = e => {
        e.preventDefault()
        loginUser();
        console.log(user)
    }

    

  return (
    <div>
      <center>
        <form onSubmit={submitHandller}>
            <input type='text' name='username' value={username} onChange={chnageHandler}/> <br/>
            <input type='password' name='password' value={password} onChange={chnageHandler}/><br/>
            <input type='submit' name='submit'/>
        </form>
      </center>
    </div>
  )
}

export default Login

error
首先,如果我没有保持良好的方法,我道歉。请帮助我解决这个问题,并给予一些好的代码实践的建议。/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

epfja78i

epfja78i1#

按如下所示更改中间件顺序。

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();
app.UseAuthorization();

app.UseSession();

app.MapControllers();
app.Run();

Asp.Net Core中中间件的顺序很重要,请参考官方推荐使用,否则很容易出错。

相关问题