简体   繁体   English

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

[英]ASP.NET CORE 3.0 application to IIS under Default Web Site/MySite does not work properly

My Asp.Net Core project runs outside of Default Web Site properly but it does not run under default web site on iis.我的 Asp.Net Core 项目在默认网站之外正常运行,但它不能在 iis 上的默认网站下运行。 Actually when I right click on application folder where under "Default Web Site" and browse mysite in chrome, it shows me login screen and address like this: https://testserver.abc.com/test_site or https://testserver.abc.com/test_site/account/login实际上,当我右键单击“默认网站”下的应用程序文件夹并在 chrome 中浏览 mysite 时,它​​会显示我的登录屏幕和地址,如下所示: https : //testserver.abc.com/test_sitehttps://testserver.abc .com/test_site/account/login

After I enter login information (the information is true i tried in local developing machine) and It can't redirect to the home/index or another link, because the link turns https://testserver.abc.com/account/login .在我输入登录信息后(我在本地开发机器上尝试过的信息是真的),它无法重定向到 home/index 或其他链接,因为链接变成了https://testserver.abc.com/account/login It is removing application folder name from link.它正在从链接中删除应用程序文件夹名称。 I could not solve this redirection problem.我无法解决这个重定向问题。 Any offer for the solution?任何解决方案的报价? Thankss..谢谢..

So that gives 404 not found error after login page.因此,登录页面后会出现 404 not found 错误。 But If I add the application folder name to link it is working properly unless you click another link :)但是如果我添加应用程序文件夹名称来链接它工作正常,除非您单击另一个链接:)

My code parts:我的代码部分:

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在此处输入图片说明

I figured out the problem.我解决了这个问题。 In my "login.cshtml " I used在我的“login.cshtml”中,我使用了

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

And I added "~" before "/" and the problem solved.我在“/”之前添加了“~”,问题解决了。

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

this applies to other menu items link as ".." instead "~".这适用于其他菜单项链接为“..”而不是“~”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在IIS默认网站下创建asp.net MVC Web应用程序或将其创建为新网站之间的区别 - Difference between creating my asp.net MVC web application ,under the IIS Default web site, or create it as a new web site 针对完整dotnet框架的ASP.NET Core Web应用程序是否可以在IIS中运行? - Does ASP.NET Core web application targeting full dotnet framework work in IIS? 如何将ASP.NET Core 5网站发布到IIS? - How to publish ASP.NET Core 5 Web Site to IIS? 驻留在ASP.NET 4 IIS网站中的ASP.NET Core Web API - ASP.NET Core Web API living inside a ASP.NET 4 IIS Web Site ASP.NET Core应用程序在IIS Express中不起作用 - ASP.NET Core application doesn't work in IIS Express 在IIS 6默认网站属性(“ ASP.NET”选项卡)中将ASP.NET版本设置为3.5。 - Set ASP.NET version to 3.5 in the IIS 6 Default Web site properties (ASP.NET tab) 在开发人员机器上将ASP.NET应用程序作为默认网站运行 - Run ASP.NET application as Default Web Site on dev machine ASP.Net Web应用程序安全性不适用于IIS 7? - ASP.Net Web Application Security dont work on IIS 7? ASP.NET-将网站发布到IIS - ASP.NET - Publishing a web site to IIS 在ASP.NET 3.5网站子文件夹下部署ASP.NET MVC 3应用程序 - Deploying ASP.NET MVC 3 Application Under ASP.NET 3.5 Web Site Sub Folder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM