-2

my program.cs file has the following code

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();

my tesst.cs controller has the following code

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");
        }
    }
}

and i have created a simple form using 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

Firstly, apologies if I wasn't maintaining good approaches. Please help me to resolve this issue and give some suggestions for good code practices. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – SpicyCatGames May 18 '23 at 12:59

1 Answers1

0

Change your middleware order like below.

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();

The order of middleware in Asp.Net Core is very important, please refer to the official recommendation to use, otherwise it is easy to make mistakes.

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • Still facing the same issue – Vamshi Krishna Vedantham May 18 '23 at 13:50
  • Access to XMLHttpRequest at 'http://localhost:5082/api/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Vamshi Krishna Vedantham May 18 '23 at 13:57
  • @VamshiKrishnaVedantham My next action is, could you create a sample project and invoke this api and add the new front-end url (http://localhost:7071), to test the cors feature in backend is working or not. If it works well, we need to review our axios request in react project. [Maybe we can try this](https://stackoverflow.com/a/62073571/7687666), I know it's not the good way to solve it, but I want to address the issue. – Jason Pan May 19 '23 at 01:35