Loading a file in MVC - c#

I have a file that needs to be read from. The problem is that if I have the FileStream open and read it everytime a request is made, the application becomes very very slow due to the size of the file (A few MB), and the fact that it runs on every request. Is there a way to read it from the beginning, then inside my Controller just refer to it?
This is my initialization code:
namespace WebsiteServer
{
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)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{*url}");
});
}
}
}
Thank you!

Related

Dependency Injection - InvalidOperationException

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Business.Abstract.IProductService' while attempting to activate 'WebApi1.Controllers.ProductsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
here is my codes
using DataAccess.Concrete.EntityFramework;
using Microsoft.AspNetCore.Builder;
namespace WebApi1
{
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)
{
//AOP
//Autofac, Ninject,CastleWindsor, StructureMap, LightInject, DryInject -->IoC Container
//AOP
services.AddControllers();
services.AddSingleton<IProductService, ProductManager>();
services.AddSingleton<IProductDal, EfProductDal>();
services.AddCors();
}
// 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();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

Loading Static Files from Controller ASP Net Core MVC

I have a puzzling problem, my application loads static files from controller folder, but in default route it loads normally
Example:
https://localhost:44369/plugins/bootstrap/js/bootstrap.bundle.min.js (in normal situation) (needs to be work)
In my situation
https://localhost:44369/Order/plugins/bootstrap/js/bootstrap.bundle.min.js
It wants to load from static files from controller folder which does not exist.
I use Admin LTE 3 Template (maybe the template has some issues?)
Thank you :)
Startup.cs
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)
{
services.AddHttpClient();
services.AddAutoMapper(typeof(Startup));
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ICustomerService, CustomerManager>();
services.AddSingleton<ICustomerDal, CustomerDal>();
services.AddSingleton<IInformationResourcesService, InformationResourcesManager>();
services.AddSingleton<IInformationResources, EFInformationResourcesDAL>();
services.AddSingleton<INewOrderService, NewOrderManager>();
services.AddSingleton<INewOrderService, NewOrderManager>();
services.AddSingleton<INewOrderDal, EfNewOrderDalL>();
services.AddSingleton<ICityDal, EFCityDal>();
services.AddSingleton<ICityService, CityManager>();
services.AddSingleton<IDisctrictDal, EFDistrictDal>();
services.AddSingleton<IDistrictService, DistrictManager>();
services.AddSingleton<IVillageDal, EFVillageDal>();
services.AddSingleton<IVillageService, VillageManager>();
services.AddSingleton<IStreetDal, EFStreetDal>();
services.AddSingleton<IStreetService, StreetManager>();
services.AddSingleton<ICustomerAdressService, CustomerAdressManager>();
services.AddSingleton<ICustomerAdressDal, EFCustomerAdressDal>();
//services.AddCors(options =>
//{
// options.AddPolicy("CorsPolicy",
// builder => builder
// .AllowAnyMethod()
// .AllowCredentials()
// .SetIsOriginAllowed((host) => true)
// .AllowAnyHeader());
//});
//services.AddDependencyResolvers(new ICoreModule[] {
// new CoreModule()
//});
}
// 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.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Customer}/{action=Index}/{id?}");
});
}
}
Can you specify how you are adding the script to your page.
I am using a template as well and my scripts are located in wwwroot/vendors folder
this is my script tag.
<script src="~/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>

React asp.net SPA calling API on same app service

I have one solution that includes two projects:
Foo - this an asp.net React site
Bar - this is an asp.net API, which the Foo projects calls
I have deployed both of these projects to one Azure app service using virtual directories.
Virtual Directory Setup
When the Foo app makes a call to https://azureFooapp.com/api/getData all that is returned is the index.html file from the Foo project. Instead of actually calling the endpoint located in the Bar API project.
If I remove the Foo project project from the App Service I am able to hit the endpoint https://azureFooapp.com/api/getData successfully.
Foo Startup.cs
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)
{
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddControllers()
.AddNewtonsoftJson();
services.AddMvc().AddNewtonsoftJson(o =>
{
o.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("/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.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
Bar Startup.cs
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)
{
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
services.AddControllers();
services.AddControllersWithViews();
services.AddControllers()
.AddNewtonsoftJson();
services.AddMvc().AddNewtonsoftJson(o =>
{
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("https://localhost").AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
}
// 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();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowSpecificOrigin");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Can anyone please help get this working? If anymore information is needed please let me know
I suggest you put the api project under wwwroot and the react project in the virtual directory.
Like :
Virtual path Physical Path Type
/ site\wwwroot Application
/pages site\wwwroot\react_folder Application
Suggestions
Why is it not recommended to put nodejs projects, such as react, angular, and vue projects into the main application?
After a lot of testing, I found that when the main application is put into these three items, the virtual application will not take effect, and it can work normally if they are put into the virtual application.
(Not recommended) After the react project is compiled, if the content of the dist folder is released, the routing access of virtual applications is supported in iis, and this is not recommended.
I have now managed to resolve this issue by modifying the code in Foo Startup.cs with the below
app.MapWhen(x => !x.Request.Path.Value.ToLower().StartsWith("/api"), builder =>
{
builder.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
});
After this I restarted the App Service

.NET Core 2.0 accessing user secrets

I'm trying to setup a .net core 2.0 web application to send an email when user registers and also to recover password. I have followed this tutorial: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?tabs=visual-studio.
However, upon reading the comments sections, it seems that the tutorial is not updated for Core 2.0. My question is, when I get to part "Add the user secrets configuration source to the Startup method", I cannot figure out how the startup file should look like since my startup file is different from the one showed there. Can anyone help me by showing me how the startup file should look like? Thanks.
This is my current startup file:
public class Startup
{
string _testSecret = null;
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)
{
_testSecret = Configuration["MySecret"];
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
services.Configure<AuthMessageSenderOptions>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var builder = new ConfigurationBuilder();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
builder.AddUserSecrets<Startup>();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
In your code I didn't find invoking of build() function of ConfigurationBuilder class. Here is the sample code.
var builder = new ConfigurationBuilder();
builder.AddUserSecrets<Startup>();
var config builder.Build(); //This line is missing from your code
string mySecret = config ['EmailAccount'];
Refernce: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-2.1&tabs=windows#access-a-secret

ASP.NET Core 2.0 IIS Web Hosting

I created an ASP.NET Core 2.0 MVC Web Application and I need help getting it setup to run with IIS on Windows Server 2016.
So far, I have followed and completed all the steps on https://learn.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x up to the section Application configuration. This is the step that I'm stuck at and have not been able to complete the steps below it.
I'm going to post my Startup.cs and Program.cs code as to what I have now. I'm not sure if those two files need modified.
Startup.cs
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)
{
services.AddDbContext<WinTenDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
The issue that I was having I finally figured it out. It had to do with the account that was setup for me on the Domain that was added to the Security on the SQL Server. Once I provided the correct permissions to that AD account I no longer received the error messages.

Categories

Resources