#angular #asp.net-core #iis
#angular #asp.net-core #iis
Вопрос:
Я новичок в мире Angular и пытаюсь развернуть ASP. СЕТЕВОЕ основное приложение с IIS на локальном сервере. В моем решении есть эти проекты
Когда я пытаюсь выполнить HTTP-запрос (например /api/Categories
) в режиме отладки, все работает нормально.
Теперь, когда я публикую приложение на локальном сервере, я могу видеть HTML-страницы, копируя файлы из dist
папки в корневую папку сервера, но каждый HTTP-запрос возвращает другую HTML-страницу, которая, похоже, index.html
. Вот еще одно изображение:
Я потратил 2 дня на поиск в Интернете, не найдя ничего, что работает. Я пытался изменить настройки прокси, параметры перенаправления, но ничего. В чем может быть проблема?
Файл Web.config
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="./index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Файл Startup.cs
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
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();
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://prf.icecat.biz");
});
});
// services.AddResponseCaching();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// 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();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
}
});
}
}
Комментарии:
1. Проблема, вероятно, связана с конфигурацией конвейера промежуточного программного обеспечения. Можете ли вы показать нам код вашего класса запуска?
2. @J.Loscos добавил код
3. Я не вижу никакой ошибки в вашем классе запуска. Есть ли у вас какие-либо правила перезаписи URL в вашей конфигурации IIS или в вашем web.config?
4. @J.Loscos Я добавил код web.config, я перепробовал все в этом файле. Теперь с этим кодом запрос возвращает 404.
5. Вы можете попробовать удалить узел <перезапись> из своего web.config. Запуск уже выполняет перезапись в index.html