I have an ASP.NET project and everything is returning a 404, here's my startup code
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();
}
// 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");
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapGet("/debug/routes", async ctx =>
{
await ctx.Response.WriteAsync(string.Join(", ", endpoints.DataSources.SelectMany(x => x.Endpoints)));
});
});
}
}
here's a sample controller:
public class Home : Controller
{
private readonly DatabaseContext _databaseContext;
public Home(DatabaseContext databaseContext)
{
Console.WriteLine($"Initialized home controller"); // This doesn't get called at all.
_databaseContext = databaseContext;
_databaseContext.Database.EnsureCreated();
}
[HttpGet("/home")]
public IActionResult Index()
{
ViewData["Products"] = _databaseContext.Products.ToList();
return View();
}
.....
and whenever I launch the server it I would go to /home and it would return 404, I also go to /debug/routes and it would show only the 2 endpoints inside the UseEndpoints function but never the controller classes I made
Try registering you db context in service as below. You could be getting error due to dependency of DatabaseContext on your HomeController would not be able to resolve.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add below line
services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connectionString));
services.AddControllersWithViews();
}
In the Configure(IApplicationBuilder app, IWebHostEnvironment env) method of the Startup class you need something like: app.MapControllers();
I think you controllers are registered to DI throught the call services.AddControllersWithViews(); but there is no middleware registration to invoke your controllers, wich should be done in the Configure method.
Related
(My English is not good)
Hello so I am having problem where when I have my web API on my server and then try to use my react website from my main pc I get Cors error. when I run both my webAPI and my react on my main pc it owrks but need it to work from the server coz we are several ppl wokring on it.
I would love it someone could help me out.
Error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ServerIP/api/user. (Reason: CORS request did not succeed).
I have tried some different things like adding:
public static void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
and then when that didn't work I tried fixing the end point
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}"
);
endpoints.MapControllers();
});
Also tried adding this infront of our two controller classes
[EnableCors("*", "*", "*")]
This is how the React looks like:
import Axios from 'axios'
const WorkifyAPI = Axios.create({
baseURL: 'https://ServerIP:42069/api'
})
export default WorkifyAPI
the react service:
import http from '../WorkifyAPI'
const GetallWorkouts = (userID: string) => {
return http.get(`/user/${userID}/WorkoutData`)
}
export default {
GetallWorkouts,
}
EDIT:
How the starup.cs Currently looks like
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 static void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapControllers();
});
}
}
When I did run my React in Chrome instead I got this Error instead:
net::ERR_CERT_AUTHORITY_INVALID
So it is something with the SSL as #sideshowbarker said so will look over that
This is the request from Devtool (?)
Declare AddCors() in ConfigureServices function and UseCors() in Configure function worked for me.
It should be like:
public void ConfigureServices(IServiceCollection services) {
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
}
The Configure function is changed depends on the version but this should work.
Try with do something like this:
services.AddCors(action =>
action.AddPolicy("AllowOrigins", builder =>
builder
//.WithOrigins("http://localhost:4200")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
)
);
tjhen in your:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowOrigins");
}
I wrote a middleware for resize image in asp.net core. but this middleware only works if browser has been not cached. first call middleware is ok but from second call, the request does not enter middleware. after clear cache in browser(ctrl+f5) the request enters middleware. How is this problem solved?
stratup.cs
namespace ImageResizer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
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.AddControllersWithViews();
services.Configure<SiteSettings>(Configuration.GetSection(nameof(SiteSettings)));
services.AddImageResizer();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseImageResizer();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
//app.UseStaticFiles();
var pathImage = Configuration.GetSection("SiteSettings").Get<SiteSettings>().ImageLocation;
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(pathImage)),
RequestPath = "/StaticFiles"
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
You can simply add some versioning to your image files, like:
<img src="filename.png?v=#Guid.NewGuid().ToString()" />
so as the file path is different, browser will not get it from cache. but please be aware that all images (that have this kind of versioning) will be downloaded every time from server effecting page load time and server load.
I have been working on project for some time now and I was able to add migrations without problem but week or two ago i transitioned from using onconfiguring optionsbuilder.useSqlServer to connect to sql server from my context class to using services from Startup class to connect to database
When I try to run add-migration i get this error
Unable to create an object of type 'mojDbContext'. For the different patterns supported at design time
Program class
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>();
});
}
startup class
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<mojDbContext>(options=> options.UseSqlServer(Configuration.GetConnectionString("ererer")));
services.AddControllersWithViews();
services.AddMvc();
services.AddDistributedMemoryCache();
services.AddSession();
}
// 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.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
my context class with removed dbset properties to keep code smaller
public class mojDbContext : DbContext
{
public mojDbContext(DbContextOptions<mojDbContext> options)
: base(options)
{
}
}
when i run add-migration -verbose i get this
https://i.stack.imgur.com/Rn7Op.png
I want to enable CORS with Asp.Net Core 3.0 API project. This is the basic generated Asp.Net Core Api template. Everything is default from the template, except I added CORS settings from the documentation: Enable Cross-Origin Requests (CORS) in ASP.NET Core
Here it is my 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.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("localhost", "www.google.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
// 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("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
And these are my response headers:
What should I set up for getting corret CORS headers in Response?
Here it is my fetch api test:
Oops, I successed to solve this.
This combination was the only one to me, what is working:
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.AddControllers();
services.AddCors(); //This needs to let it default
}
// 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(
options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
); //This needs to set everything allowed
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
If you put the API URL directly in the browser, CORS is not involved.
It isn't a cross-origin request.
That only happens when you have a page hosted at one origin, e.g. localhost:5000, which has JavaScript code that calls an API at origin localhost:5001.
(or otherwise fetches resources from another origin)
But in your case the only origin is the API origin and thus CORS is not needed.
I was developing a Web-App with Asp.Net Core 2.1 . After I added the new identity with scaffolder it generated me these codes:
Code generated in IdentityStartup.cs
[assembly:HostingStartup(typeof(ShareAndCare.Areas.Identity.IdentityHostingStartup))]
namespace ShareAndCare.Areas.Identity
{
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
services.AddDbContext<ShareAndCareContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(
context.Configuration.GetConnectionString("ShareAndCareContextConnection")));
services.AddIdentity<ShareAndCareUser, IdentityRole>()
.AddEntityFrameworkStores<ShareAndCareContext>()
.AddDefaultTokenProviders();
services.AddSingleton<IEmailSender, EmailSender>();
});
}
}
}
Code generated in Startup.cs
namespace ShareAndCare
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
This was working fine until I wanted to scaffold a model with controller and views using EF. When set up everything and click ok I was getting an error saying : More than one DbContext named 'ShareAndCare.Models.ShareAndCareContext' was found. Specify which one to use by providing its fully qualified name using its exact case. I checked all the folders and namespaces but there was no problem there, there was only one context with that name. So what was the problem ?
I'm leaving that question and answer here so people don't go crazy looking for all possible solutions manually like I did. I found out that adding the context in the Configure method of IdentityHostingStartup.cs was causing the problem. I changed the place where I added the context to the Configure method of Startup.cs and it was working just fine.
namespace ShareAndCare
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<ShareAndCareContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(
Configuration.GetConnectionString("ShareAndCareContextConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
I just deleted the 2 files:
Areas/Identity/Data/APNameIdentityDbContext.cs and
Areas/Identity/IdentityHostingStartup.cs
This fixed the error!
In my Case I was adding
services.AddDbContext<DBContext>
but instead my DBContext name was
ApplicationDBContext.
Changed my Name in Startup.cs and it worked
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration["Data:ConnectionStrings:DefaultConnection"]));
}
Hope this helps someone :)