ASP.NET Core 6 MVC published to local IIS routing not working HTTP 500 error - iis

I have published an ASP.NET Core 6 MVC web application to my local IIS. The site loads without error, however the routing doesn't work and I am left with a HTTP 500 error when navigating from the home page.
The routing works when I build and load directly from Visual Studio. I am not sure what elements you would need to help me with this, but here is my program.cs.
Help please :). Richard
using Microsoft.EntityFrameworkCore;
using RabsoInc.Web.DAL;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
builder.Services.AddMvc();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("default")));
builder.Services.AddTransient<IDomain, DomainRepo>();
builder.Services.AddTransient<IItem, ItemRepo>();
var app = builder.Build();
app.UseRouting();
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.Run();

Related

openapi.json not found when hosting NetCore 3.1 Web Api on IIS

I generated my server stub for ASP.NET Core 3.1 using the openapi generator with the following command:
npx #openapitools/openapi-generator-cli generate -i myapi.json -g aspnetcore -o C:\myapi --additional-properties aspnetCoreVersion=3.1
After opening that project in Visual Studio 2019 and running it I get the swagger page where I can try out the different endpoints. So far OK.
However: after publishing this on our IIS Server and visiting the proper URL that swagger page is loading with the error:
Not found: /swagger/1.0.0/openapi.json
Swagger error on IIS
The endpoint itself (GET request) can be reached.
The Swagger Endpoint code in startup.cs is the default code as it was generated by open-api generator:
app.UseSwagger(c =>
{
c.RouteTemplate = "swagger/{documentName}/openapi.json";
})
.UseSwaggerUI(c =>
{
//TODO: Either use the SwaggerGen generated Swagger contract (generated from C# classes)
c.SwaggerEndpoint("/swagger/1.0.0/openapi.json", "Swagger WP RUH Delivery");
//TODO: Or alternatively use the original Swagger contract that's included in the static files
// c.SwaggerEndpoint("/openapi-original.json", "Swagger WP RUH Delivery Original");
});
Why is this Swagger page working on my machine, but on IIS things go wrong?
I found some hints on changing the c.SwaggerEndpoint in startup.cs, but nothing helped.
Try to remove /swagger/ from the URL path:
c.SwaggerEndpoint("1.0.0/openapi.json", "Swagger WP RUH Delivery")

mapbox files pbf blocked IIS server

PBF (street map mapbox vector files) files are not allowed to be served /downloaded from IIS (2008 R8) and I need them to be.
The background
PBFs are served OK when using the react development server
//Startup.cs
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
These files will appear on the map correctly.
However when deploying the .NET Core app to IIS with
ASPNETCORE_ENVIRONMENT = production
set. These files are essentially blocked.
I have added the MIME type
I believe this is an IIS thing as like I say, on the react server in development they load fine.
Any clues as of why they still won't download?
Thanks
Basically IIS virtual directories aren’t supported in .net core. Due to the way .net core projects are served in IIS using a reverse proxy. So in the startup.cs file, do something like this:
// Configure the virtual directory
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(#"\\Server\Directory\.."),
RequestPath = "/NameOfDirectory",
ContentTypeProvider = provider,
OnPrepareResponse = (context) => {
if (!context.Context.User.Identity.IsAuthenticated) {
context.Context.Response.Redirect("LoginPage");
}
}
});

Azure does not see Index.cshtml

I'm trying to publish my ASP.NET Core application on Azure service. This works, but when I try to use the application functionality, I get the message
Your App Service app is up and running.
Moreover, in my wwwroot folder I don't have any .html files. I only have an Index.cshtml file, which is located in the Views/Home-folder in my application, all another files are .css, .js, etc.
When I run the application in Visual Studio in Debug mode, immediately opens the page in browser that was generated from Index.cshtml. But after the application is published in Azure, this does not happen.
What can I do to make Azure see Index.cshtml?
AFAIK, a default route would be added to Configure method of your Startup.cs file as follows:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I also created my .Net Core 2.0 MVC application to check this issue, it could work as expected on local side and my azure web app.
Moreover, in my wwwroot folder I don't have any .html files.
Views under Web Application and Web Apllication MVC would be compiled into {your-webapplication-assemblyname}.PrecompiledViews.dll, you could leverage ILSpy to check your DLLs.
For your issue, I would recommend you clear the web content in your web app via KUDU, or modify the publish settings and choose Remove additional files at destination under File Publish Options, then redeploy your application to Azure Web App to narrow this issue.
Are you finding index.cshtml in your web package? In case if you get index.cshtml in your final web package, you may need to add index.cshtml file type to the following in..
..YourAzureWebApp --> Application Settings --> Default Documents
I found out what the problem was. There are two types of applications, as presented below in the picture: Web Application and Web Apllication MVC. I worked with the second type of application. When I selected the first type and published the application, Azure immediately found the required index.html. I just had to choose Web Application.
But why does not it work with the second type of application (Web Apllication MVC)? I still do not know the answer to this question.
2 cents from my side as I just stuck for a while with this.
The problem was that yesterday I'd been playing around with deploying to Ubunut / Ngnix and today I decided to try Azure.
BUT I forgot to comment (disable) the following lines in my Startup:
//for nginx server
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
and that costed me almost half of the day to find the issue.
I also put the routing in the following way
app.UseStatusCodePages();
app.UseAuthentication();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Pages}/{action=Index}");
});
Now looks like it works on Azure :)

How to Publish ASP.NET Core WEB API Project on Local IIS in Visual Studio 2017 Community RC?

I want to publish ASP.NET Core WebAPI Project with swagger on IIS. i want to run the Project on local machine with IP Address.
Configuration of My PC is:
Visual Studio 2017 Community RC
Windows 10
IIS
Please help me.
Have you tried "this one (learn.microsoft.com)"?
It helped for me. Don't forget to configure authentication and access to your site physical path for application pool identity you are going to use.
UPD (reply to comment):
In case you're using Swashbuckle.AspNetCore package you can try somethig like this in your ConfigureServices(IServiceCollection services):
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
var info = new Info
{
Title = "My web API",
Version = "v1.0",
Contact = new Contact()
{
Email = "foo#gmail.com",
Name = "Denis",
Url = "https://stackoverflow.com"
},
Description = "My API"
};
c.SwaggerDoc("v1.0", info);
var basePath = AppContext.BaseDirectory; // this is not equal to wwwroot folder due to WebHostBuilder settings
var xmlPath = Path.Combine(basePath, "MyApi.xml");
c.IncludeXmlComments(xmlPath);
});
And in Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory):
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My web API v1.0");
c.EnableDeepLinking();
});

IIS 8.5 MVC 5 Routes 'api/controllerName' gives 404 Not Found Error

Within a MVC 5 Webapi project, I am trying to do a GET request via jquery using URL 'api/controllerName'. The web application is hosted under Default Website and the root of the webisite is "localhost/myApp".
The route 'api/controllerName' gets translated to 'localhost/api/controllerName' instead of 'localhost/myApp/api/controllerName' throwing 404 Not found Error.
This has to do something with IIS 8.5 and MVC 5 routing, because:
The Same setup works well on IIS 7.5
The same set up works well on IIS 8.5 if i do not use a virtual directory and host the application directly at Default Web Site.
My Global.asax.cs's RegisterRoutes Method looks like below
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I figured this out. Apparently, IIS 7.5 worked fine with the bare route 'api/controllerName' but IIS 8.5 needed a fully qualified route created using #Url.RouteURL utility with RouteName as "DefaultApi".
i replaced the URL with
'#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "controllerName"})'
and it worked like a charm (on both IIS 7.5 and IIS 8.5).

Resources