So I have everything set up with an oracle db. The API runs fine and my angular app is able to send get requests to it just fine, but my post requests don't seem to work. I have some custom authorization middleware. Now I know that it isn't the AUTH since all my get requests run fine.
The error is as follows:
Access to XMLHttpRequest at 'https://localhost:44342/api/User/insertUser' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is an example of a post in one of my angular services
insertUser(model: Users_Viewmodel) {
console.log(model);
return this.http.post<Users_Viewmodel>(
`${this.apiUrl}/api/User/insertUser`, model
);
}
Now on my API side I have CORS set up in my Startup.cs:
// outside of my ConfigureServices method
readonly string MyAllowOrigins = "_myAllowOrigins";
// in my ConfigureServices method
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowOrigins,
policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
// In my Configure method
app.UseCors(MyAllowOrigins);
Lastly I have this in my API controller "UserController"
[HttpPost("insertUser")]
[Authorize]
public IActionResult InsertUser([FromBody] Users_Viewmodel model)
{
try
{
UserRepo.InsertUser(model);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Edit: Added all StartUp.cs code on request
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MyApp.Api.Helpers;
using MyApp.Api.MiddleWare;
using MyApp.WebSocketHub;
namespace MyApp.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
readonly string MyAllowOrigins = "_myAllowOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add session-related configuration at the beginning of the method
services.AddDistributedMemoryCache(); // Add this line
services.AddSession(options =>
{
options.Cookie.Name = "SessionVars";
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddHttpContextAccessor();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<SessionManager>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowOrigins,
policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
services.AddSignalR()
.AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = new AllUppercaseNamingPolicy();
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyApp.Api", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyApp.Api v1"));
}
app.UseCors(MyAllowOrigins);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseMiddleware<OpcAuthorizeMiddleware>();
SessionManager.Initialize(httpContextAccessor);
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<WebSocketHub.WebSocketHub>("/ws");
endpoints.MapControllers();
});
}
}
}
Try adding
[EnableCors("_myAllowOrigins")]
at the start of your controller.