ASP.NET CORE 3.0应用程序到默认网站/ MySite下的IIS无法正常工作

问题描述 投票:1回答:1

我的Asp.Net Core项目可以在默认网站之外正常运行,但是不能在iis的默认网站下运行。实际上,当我右键单击“默认网站”下的应用程序文件夹并以chrome浏览mysite时,它显示出我的登录屏幕和地址,如下所示:https://testserver.abc.com/test_sitehttps://testserver.abc.com/test_site/account/login

输入登录信息后(该信息是真实的,我在本地开发机器上尝试过),并且无法重定向到home / index或其他链接,因为该链接变为https://testserver.abc.com/account/login。它正在从链接中删除应用程序文件夹名称。我无法解决此重定向问题。有解决方案的报价吗?谢谢..

因此,登录页面后将显示404 not found错误。但是,如果我添加应用程序文件夹名称以进行链接,则除非您单击其他链接,否则它将正常工作:)

我的代码部分:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        IdentityModelEventSource.ShowPII = true;

        services.AddDbContext<LabStokContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


        services.AddMvc().AddNToastNotifyNoty();

        //Not: Dependency hizmetleri ayrı bir sınıfta çağırılıyor
        services.ServisEkle();

        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        Encoding.GetEncoding("UTF-8");

        services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

        services.AddCors(options =>
        {
            options.AddPolicy("AllowOrigin",
                builder => builder.WithOrigins("http://localhost:80/", "https://localhost:443/"));
        });


        var tokenOptions = Configuration.GetSection("TokenOptions").Get<TokenOptions>();

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login/";
            });

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }
            )
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.IncludeErrorDetails = true;
                options.RequireHttpsMetadata = false;

                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidIssuer = tokenOptions.Issuer,
                    ValidAudience = tokenOptions.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey),
                    ClockSkew = TimeSpan.Zero
                };

            });


        services.AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
        });

        services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

        services.AddMvc(option => option.EnableEndpointRouting = false)
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }


        app.UseHttpsRedirection();            

        app.UseStaticFiles();

        app.UseRouting();

        app.UseCors(builder => builder.WithOrigins("http://localhost:80", "https://localhost:443").AllowAnyHeader());

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseNToastNotify();

        app.UseMvc(routes =>
        {

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}");
        });

    }
}


public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)

            .ConfigureWebHostDefaults(webBuilder =>
            {

                webBuilder.UseStartup<Startup>();
            });
}

public class AccountController : Controller
{

    private readonly IKisiService _kisiService;

    private readonly IAuthService _authService;

    private readonly ITokenHelper _tokenHelper;


    public AccountController(IKisiService kisiService, IAuthService authService, ITokenHelper tokenHelper)
    {

        _kisiService = kisiService;
        _authService = authService;
        _tokenHelper = tokenHelper;

    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public IActionResult Login(UserForLoginDto userForLoginDto)
    {

        Task<OrgPerson> userToLogin = _authService.CheckUserToLogin(userForLoginDto);

        if (userToLogin.Result == null)
            return BadRequest(userToLogin.Result);

        kisi user = _kisiService.KisiGetirEPostaIle(userToLogin.Result.KullaniciAdi);

        if(user==null)
            return RedirectToAction("Login", "Account");


        var result = _authService.CreateAccessToken(user); 

        ClaimsPrincipal principal = _tokenHelper.GetClaimsPrincipal(result.Token);

        HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal));

        if (result != null)
        {

            return RedirectToAction("Index", "Home");
        }

        return BadRequest(user);

    }



}

//launchsettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:15798",
      "sslPort": 44300
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "LabStokTakip": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
    

    }
  }
}

//appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=******;Database=******;User Id=*****;Password=******;"
  },
  "TokenOptions": {
    "Audience": "https://localhost:5001/",
    "Issuer": "https://localhost:5001/",
    "AccessTokenExpiration": 10,
    "SecurityKey": "************************************************************"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

enter image description here

asp.net .net web-deployment core iis-8
1个回答
0
投票

我想出了问题。在我的“ login.cshtml”中,我使用过

<form action="/Account/Login" method="post" class="pt-2" >

并且我在“ /”之前添加了“〜”,并且问题解决了。

 <form action="~/Account/Login" method="post" class="pt-2" >

这适用于其他菜单项链接为“ ..”而不是“〜”。

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