4

I am working on an Asp.Net-Core-2.0 web API project. I published the web API to IIS, now when I try to access it, it gives me a 404 Error message in all controllers.

I have tried to google everything but nothing has helped me.

If anybody requires any information please leave a comment under the question and I will update my question.

Program.cs file

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

        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
                   .UseStartup<Startup>()
                   .Build();
    }

Startup.cs file

public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                   .SetBasePath(env.ContentRootPath)
                   .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                   .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                   .AddEnvironmentVariables();
            Configuration = builder.Build();

            //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)
        {
            services.AddScoped<AuthRepository>();
            services.AddSingleton<IKapanRepository, KapanRepository>();
            services.AddSingleton<IDepartmentRepository, DepartmentRepository>();
            services.AddSingleton<IPriorityRepository, PriorityRepository>();
            services.AddSingleton<IPlanRepository, PlanRepository>();
            services.AddSingleton<IRuleTemplateRepository, RuleTemplateRepository>();
            services.AddSingleton<IDamageReportRepository, DamageReportRepository>();
            services.AddSingleton<IDashBoardRepository, DashBoardRepository>();
            services.AddSingleton<IPacketRepository, PacketRepository>();
            services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
            services.AddSingleton<IPriceCalculatorRepository, PriceCalculatorRepository>();
            services.AddSingleton<ISearchRepository, SearchRepository>();
            services.AddSingleton<IUserInfoRepository, UserInfoRepository>();
            services.AddSingleton<IOverLossRepository, OverLossRepository>();

            // Container could be configured via services as well. 
            // Just be careful not to override registrations
            services.AddDbContext<ApplicationContext>(opts =>
                   opts.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            // Add framework services.
            services.AddMvc();
            services.AddIdentity<ApplicationUser, IdentityRole>(options => {
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddEntityFrameworkStores<ApiDbContext>()
            .AddDefaultTokenProviders();
            services.AddDbContext<ApiDbContext>(options => options.UseSqlServer(Settings.ConnectionStringAuth));

            // return 401 instead of redirect to login
            services.ConfigureApplicationCookie(options => {
                options.Events.OnRedirectToLogin = context => {
                    context.Response.Headers["Location"] = context.RedirectUri;
                    context.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };
            });

            services.AddAuthentication(sharedOptions => {
                sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                      .AddJwtBearer(cfg => {
                          cfg.RequireHttpsMetadata = false;

                          cfg.TokenValidationParameters = new TokenValidationParameters() {
                              ValidateIssuer = true,
                              ValidateAudience = true,
                              ValidateLifetime = true,
                              ValidateIssuerSigningKey = true,
                              LifetimeValidator = CustomLifetimeValidator,
                              ValidIssuer = Configuration["TokenAuthentication:Issuer"],
                              ValidAudience = Configuration["TokenAuthentication:Audience"],
                              IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["TokenAuthentication:client_secret"]))
                          };

                          cfg.Events = new JwtBearerEvents {
                              OnAuthenticationFailed = context => {
                                  Console.WriteLine("OnAuthenticationFailed: " +
                                      context.Exception.Message);
                                  return Task.CompletedTask;
                              },
                              OnTokenValidated = context => {
                                  Console.WriteLine("OnTokenValidated: " +
                                      context.SecurityToken);
                                  return Task.CompletedTask;
                              }
                          };

                      });
            services.Configure<IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
            });
        }

        private bool CustomLifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
        {
            if (expires != null) {
                return expires > DateTime.UtcNow;
            }
            return false;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMiddleware<TokenProviderMiddleware>();
            app.UseMiddleware<RefreshTokenProviderMiddleware>();
            app.UseAuthentication();
            app.UseMvc();
        }
    }

Any help will be appreciated.

Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95

1 Answers1

0

Yes I got it..

After finding to Google and SO nothing is help me. After doing myselft Instead of taking Web Api project I am taking Web Applicaton project and publish on IIS it's work like a charm

Try it.

Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95