ASP.NET Core 6 之后的 Program.cs 文件

问题描述 投票:0回答:2

我用 ASP.NET Core 6 编写了一个简单的令牌生成 API。我需要进行集成测试。当我编写集成测试时,它需要引用 Program 类,但我收到错误

由于保护级别,“程序”元素无法访问

所以在添加命名空间和公共之后,我收到错误

CS0017:程序中定义了多个入口点。指定 /main 来指定包含入口点的类型。

我无法解决。

这是我的

Program.cs
:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using TokenProject.Model;


var builder = WebApplication.CreateBuilder(args);

// CORS yapılandırması
builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowAngularApp",
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:4200") // Angular uygulamasının adresi
                               .AllowAnyHeader()
                               .AllowAnyMethod()
                               .AllowCredentials(); // Credentials ekledim
                    });
            });

// JWT kimlik doğrulama yapılandırması
builder.Services.AddAuthentication(options =>
           {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("Token validation failed: " + context.Exception.Message);
                        return Task.CompletedTask;
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("Token validated: " + context.SecurityToken);
                        return Task.CompletedTask;
                    }
                };
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
                };
            });

builder.Services.AddDbContext<TokenDbContext>(options =>
                options.UseSqlServer(builder.Configuration.GetConnectionString("TokenDB")));

// Add services to the container.
builder.Services.AddControllers();
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();

// CORS politikasını kullan
app.UseCors("AllowAngularApp");

// Authentication ve Authorization'ı kullan
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

TokenControllerTests

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json;
using Xunit;

namespace Token.IntegrationTests
{
    public class TokenControllerTests : IClassFixture<WebApplicationFactory<Program>>
    {
        private readonly HttpClient _client;

        public TokenControllerTests(WebApplicationFactory<Program> factory)
        {
            _client = factory.CreateClient();
        }
        
        [Fact]
        public async Task Get_Token_Endpoint_Returns_Success()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "/api/token");
            var response = await _client.SendAsync(request);
            response.EnsureSuccessStatusCode();
        }

        [Fact]
        public async Task Post_Token_Returns_Success()
        {
            
            var tokenRequest = new
            {
                Username = "testuser",
                Password = "P@ssw0rd"
            };

            var content = new StringContent(JsonConvert.SerializeObject(tokenRequest), Encoding.UTF8, "application/json");

            
            var response = await _client.PostAsync("http://localhost:7125/api/Auth/login", content);
            
            response.EnsureSuccessStatusCode();
        }
    }
}
asp.net-core-webapi token integration-testing xunit asp.net-core-6.0
2个回答
0
投票

将以下代码添加到您的

Program.cs
末尾(即在
app.Run();
之后添加代码):

app.Run();  
public partial class Program { }

0
投票

我尝试了这个方法,但结果是一样的

© www.soinside.com 2019 - 2024. All rights reserved.