.NET 5核心API与Angular前端代码问题

9bfwbjaz  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(120)

所以我用一个oracle数据库设置好了一切。API运行正常,我的angular应用程序能够很好地向它发送get请求,但我的post请求似乎不起作用。我有一些自定义的授权中间件。现在我知道它不是AUTH,因为我所有的get请求都运行正常。
错误如下:

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.

字符串
下面是我的一个角服务中的一个帖子的例子

insertUser(model: Users_Viewmodel) {
  console.log(model);
  return this.http.post<Users_Viewmodel>(
    `${this.apiUrl}/api/User/insertUser`, model
  );
}


现在,在我的API端,我在Startup.cs中设置了CORS:

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


最后,我在我的API控制器“UserController”中有这个。

[HttpPost("insertUser")]
[Authorize]
public IActionResult InsertUser([FromBody] Users_Viewmodel model)
{
    try
    {
        UserRepo.InsertUser(model);
        return Ok();
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}


编辑:根据要求添加了所有StartUp.cs代码

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

xzlaal3s

xzlaal3s1#

尝试在控制器的开头添加[EnableCors("_myAllowOrigins")]

[EnableCors("_myAllowOrigins")]
[HttpPost("insertUser")]
[Authorize]
public IActionResult InsertUser([FromBody] Users_Viewmodel model)
{
    try
    {
        UserRepo.InsertUser(model);
        return Ok();
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

字符串

相关问题