I've got a very simple angular app project that needs to do nothing more than serve static files from wwwroot. Here is my Startup.cs:
public class Startup
{
public void ConfigureServices(IServiceCollection services) { }
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
Whenever I launch the project with IIS Express or web I always have to navigate to /index.html. How do I make it so that I can just visit the root (/) and still get index.html?
You want to server default files and static files:
public void Configure(IApplicationBuilder application)
{
...
// Enable serving of static files from the wwwroot folder.
application.UseStaticFiles();
// Serve the default file, if present.
application.UseDefaultFiles();
...
}
Alternatively, you can use the UseFileServer method which does the same thing using a single line, rather than two.
public void Configure(IApplicationBuilder application)
{
...
application.UseFileServer();
...
}
See the documentation for more information.
Simply change app.UseStaticFiles(); to app.UseFileServer();
public class Startup
{
public void ConfigureServices(IServiceCollection services) { }
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseFileServer();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
Related
public void Configuration(IAppBuilder app)
{
// code is executed
}
public void ConfigureServices(IServiceCollection services)
{
// code is not executed
}
ConfigureServices(IServiceCollection services) method is only available in ASP.NET Core.
this might help- ASP.NET Classic OWIN StartUp ConfigureServices not called
Based on OWIN Startup Class Detection, you have to add the NuGet package Microsoft.Owin.Host.SystemWeb and then reference a OWIN Startup class from VisualStudio template, then in the following code you can access OWIN:
[assembly: OwinStartup("ProductionConfiguration", typeof(StartupDemo.ProductionStartup2))]
namespace StartupDemo
{
public class ProductionStartup
{
public void Configuration(IAppBuilder app)
{
app.Run(context =>
{
string t = DateTime.Now.Millisecond.ToString();
return context.Response.WriteAsync(t + " Production OWIN App");
});
}
}
public class ProductionStartup2
{
public void Configuration(IAppBuilder app)
{
app.Run(context =>
{
string t = DateTime.Now.Millisecond.ToString();
return context.Response.WriteAsync(t + " 2nd Production OWIN App");
});
}
}
}
i've the following problem: i've a web service application that uses ServiceStack. I'd like to register as base path "/api", but even if I set DefaultRedirectPath to "/api/metadata", when i start the app it won't redirect automatically (if i type "/api/metadata" all works)
Can anyone help me? Here's my code inside AppHost
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
DefaultRedirectPath = "/api/metadata"
});
}
public class Startup
{
public IConfiguration Configuration { get; }
public Startup()
{
Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
}
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseServiceStack(new AppHost
{
PathBase = "/api",
AppSettings = new NetCoreAppSettings(Configuration)
});
}
}
Thanks in advance and sorry for my english
Firstly I'd consider not using an /api PathBase which would disable the new /api route. E.g. if you didn't have a /api PathBase you would automatically be able to call a Hello API from /api/Hello.
But if you you still want to host ServiceStack at a custom /api path know that this is the path that ServiceStack will be mounted at, i.e. from where ServiceStack will be able to receive any requests.
Which also means you should just use /metadata which will redirect from where ServiceStack is mounted at, so if you had:
public class AppHost : AppHostBase
{
public AppHost() : base("MyApp", typeof(MyServices).Assembly) {}
public override void Configure(Container container)
{
SetConfig(new HostConfig {
DefaultRedirectPath = "/metadata"
});
}
}
Then calling https://localhost:5001/api will redirect to https://localhost:5001/api/metadata.
ServiceStack can only see requests from /api where it's mounted at, so if you wanted to redirect the / route to the metadata page you would need to register a custom ASP.NET Core handler to do it, e.g:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseServiceStack(new AppHost {
PathBase = "/api",
});
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapGet("/", async context =>
context.Response.Redirect("/api/metadata"));
});
}
Note: you no longer need to set NetCoreAppSettings() which is populated by default
Hello i am trying to understand why do my requests not enter my api route.They seem to reach the server but they wont fan out in the MVC.
The server is running on: http://localhost:9300
The route i am requesting is : http://localhost:9300/api/getusers
Program
public class Program {
public static void Main(string[] args) {
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
var builder = new WebHostBuilder();
builder.UseStartup<Startup>();
var url = Address.Default.ToUrl();
builder.UseKestrel().UseUrls(url);
return builder;
}
}
Startup
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
services.AddMvc();
}
public IConfiguration Configuration;
public void Configure(IApplicationBuilder app) {
Debug.WriteLine("Entered server"); //enters successfully here
app.UseMvc(); //does not enter the controller
}
}
Controller
This is a simple controller with a GET method.The constructor is not invoked at all.Why would this happen?I know it when the server runs the first time ..it does a health check on its routes.
[ApiController]
class UserController : ControllerBase {
private static List<User> users = new List<User> {
new User{Id=0,Age=0,Name="Failed"},
new User{Id=12,Age=33,Name="Daniel"},
new User{Id=13,Age=33,Name="Marian"},
};
public UserController() {
Debug.WriteLine("Controller called"); //does not get called !
}
[HttpGet]
[Route("api/getusers")]
public async Task<HttpResponseMessage> GetUsers() {
await Task.Delay(1000);
return new HttpResponseMessage {
Content = new StringContent(users.ToJson()),
StatusCode = HttpStatusCode.OK
};
}
}
P.S Do i have to add anyything ? What am i missing i followed other implementations closely.
I've created the webapi project using dotnet new webapi.
I've managed to get to the url with the similar configuration by changing the access modifier of a similar controller. Try to add public keyword to the class UserController. So it should be public class UserController
I will provide more information about the configuration of the project if it is necessary and the step above does not help.
What the simplest way to convert a file path to a absolute url. Example:
file:
C:\myapp\src\SqlExpress\wwwroot\data\images\test.jpg
url:
http://localhost/data/images/test.jpg
This is what I did. I never could find a way to easily find the wwwroot path outside a controller. So I used a static variable in Startup class, which is accessible throughout the application.
public class Startup
{
public static string wwwRootFolder = string.Empty;
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
Startup.wwwRootFolder = env.WebRootPath;
// ...
}
}
Then in wherever I want..
public static string GetUrlFromAbsolutePath(string absolutePath)
{
return absolutePath.Replace(Startup.wwwRootFolder, "").Replace(#"\", "/");
}
static string Convert(string path)
{
return path.Replace(#"C:\myapp\src\SqlExpress\wwwroot", #"http://localhost").Replace('\\', '/');
}
static void Main(string[] args)
{
string url = Convert(#"C:\myapp\src\SqlExpress\wwwroot\data\images\test.jpg");
}
How can I add a custom resource location that is on for example my D drive in folder called Resources.
#Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/**").addResourceLocations("D:/Resources/");
}
}
This doesn't work.
This is my application class and the only other configuration file.
#SpringBootApplication
public class Application {
public static void main(String args[]){
SpringApplication.run(Application.class, args);
}
#Bean // for websocket endpoints
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
#Bean
public PasswordEncoder bcryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
You should state your location using the file prefix, check more here . So it should be
registry.addResourceHandler("/**").addResourceLocations("file:///D:/Resources/");
Try /D:/Resources/. Absolute path must start with /