I am in MVC Core application. I added System.Web to my using clause but still I cannot access httpcontext.Session. The intellisense does not give me any option for httpcontext. Thanks for your answer.
Edit:
I have found this answer: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/
But when I add the nuget package: Microsoft.AspNetCore.Session into my project the solution won't even load anymore. So I had to remove it
Edit: Now I have added the most recent version of the package from nuget console. But I still do not have HttpContext option in the intellisense so I cannot access the session. Please help..
In System.Web I have only the following object: HttpUtility and nothing more,
is there anyone that can help? Without Sessions I cannot write any applications. Should I reinstall Visual Studio?
Notice**: In my webforms application I have the object Session in system.web
As required I post my Startup.cs and the file in which I am trying to call the object Session:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Localization;
using WebCoreFly.Models;
namespace WebCoreFly
{
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();
services.AddDbContext<FlyDBContext>(options =>
options.UseSqlServer(Configuration["Data:WebCoreFly:ConnectionString"]));
services.AddSingleton<FlyRepository>();
}
// 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.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
the class in whic I am trying to call session:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace WebCoreFly.Models.ViewModels
{
public class UserRepository1
{
public UserRepository1()
{
System.Web.HttpContext //does not recognize it
}
}
}
Related
I'm new to ASP .NET Core, however I've had coded ASP .NET before, now I am following this tutorial
"https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio-code".
I am using Visual Studio Code.
I'm doing the "Scaffold a controller" section.
When I run the last dotnet statement, stated in that section, I get the error that I refer on the title (same error that shows on my problems tab inside the terminal).
Problem is, that the error can be resolved by inserting a "using" statement, as it's shown on the section "Register the database context".
I have followed thoroughly all the steps, but when it comes to using TodoApi.Models, I get the error
Type or namespace name 'Models' does not exist in namespace 'TodoApi' (assembly reference missing?) [TodoApi]
I have read many threads but none seem to answer the question regarding my specific case, here I'll show some of my code so you can compare mine with the Tutorial's
My Startup.cs file:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
namespace TodoApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I'm totally new to ASP.NET. I wanted to create small API. I tried to connect that API with Microsoft Sql Server. But it gives an error which is
InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc' inside the call to 'ConfigureServices(...)' in the application startup code
My Startup.cs file is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
//using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;
using myApp.Models;
namespace myApp
{
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)
{
var connection = #"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
}
// 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.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
That error is indicate in app.UseMvc(); . Can you anyone help me to solve this problem?
after the services.AddDbContext …
just add services.AddMvc()
(just as the error Msg suggested )
public void ConfigureServices(IServiceCollection services)
{
var connection = #"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
services.AddMvc()
}
I see an official video of visual studio show how to do this. But in the end, the instructor can't make it work, he must alter UseSqlServer() with UseInMemoryDatabase() in Startup.cs.
Here is my code, i follow his instruction.
Firstly, create a file with classes that one contain Dbcontext, others map with tables in database. In my case, database just have one table: Students. This is class contain Dbcontext:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HoangHoaTham.WebAPI.Entities
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options) : base(options)
{
}
public DbSet<Students> Students;
}
}
My Startup.cs, i add UseSqlServer here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HoangHoaTham.WebAPI.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HoangHoaTham
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(options
=> options.UseSqlServer(Configuration.GetConnectionString("HoangHoaTham")));
services.AddMvc();
}
//You don't need to reed the code below
// 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.UseMvc();
}
}
}
Finally, I add ConnectionString into appsetting.json:
{
"ConnectionString": {
"HoangHoaTham": "Server=PC-PC\\SQLEXPRESS;Database=HoangHoaThamHighSchool;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Anh it doesn't work. The error :
enter image description here
Here is his video: https://www.youtube.com/watch?v=aIkpVzqLuhA
Skip to 50:47 to see how he did that.
Thank you so much.
The error is telling you that the result of Configuration.GetConnectionString("HoangHoaTham") is null. Therefore, there's some issue with your configuration, and it turns out there is: the connection string section in appsettings.json is supposed to be ConnectionStrings (plural). You've got ConnectionString (singular) instead.
The error is for the ConnectionString you used in appsetting.json just try this code in your appsetting.json1 and tweak the connectionstring` as per your requirements this would work.
ASP.NET Core Web API
{
"ApplicationInsights":{
"InstrumentationKey":""
},
"ConnectionStrings":{
"DefaultConnection":"Server=srvrName;Database=Test;User Id=User;Password=pass"
},
"Logging":{
"LogLevel":{
"Default":"Warning"
}
},
"AllowedHosts":"*"
}
What is the alternative for context.Response.SetValidUntilExpires(true) in asp.net core?
I checked the headers in an asp.net app, and could not find any changes on setting the flag as true or false.
context.Response.Cache.SetExpires(DateTime.Now.AddDays(7));
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
Whenever you want to cache something, do not trust the client. The client can easily ignore it and ask your API again and again.
A better approach would be to use server side caching techniques.
However, it is possible to use the ResponseCacheAttribute to solve your issue. Here is an example.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
[ResponseCache(Duration = 123, VaryByHeader = "User-Agent")]
public IEnumerable<string> Get()
{
return new string[] {"value1", "value2"};
}
}
}
In case you are serving static files. Caching is achieved by configuring it in the Startup.cs File of your project.
Here is an example:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Net.Http.Headers; // required
namespace WebApplication1
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var durationInSeconds = (int) TimeSpan.FromDays(1).TotalSeconds;
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
context.Context.Response.Headers[HeaderNames.CacheControl] =
$"public,max-age={durationInSeconds}";
}
});
app.UseMvc();
}
}
}
I'm trying to use Quartz sheduker in my asp core 2.0 project.
I downloaded Quartz 3.0.4 using nuget and after that i added services.AddQuartz(new QuartezOptions {});
to ConfigureService function in Startup.cs
I also have the same problem with app.UseQuartz()
Thats, how Startup.cs is looking now:
using AspProj.Map;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Quartz;
namespace AspProj
{
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<CacheDbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DB")));
services.AddScoped<CacheDbContext>();
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" });
});
services.AddQuartz(new QuartezOptions { });
}
// 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.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "DbApi V1");
});
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseQuartz();
}
}
}
I tried to connect different Quartz namespaces through using, but it has no use.
I just keep getting "IServiceCollection does not contain definition for AddQuartz" from visual studio 2017.
error screenshot
I cant find any information about someone with the same problem as me.
Did sombody knows, how can i fix this?
Try to add the Quartz namespace in your dependencies and this should work:
using Quartz;
Also ensure that the proper package has been installed:
dotnet add package Quartz.Extensions.Hosting
need to install package Quartz.NET Microsoft.Extensions.DependencyInjection