Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Путь через компоненты
Сквозные компоненты, которые образуют конвейер между сервером и приложением, которое выполняет инспекцию, маршрутизацию или изменении запроса и ответа с определенной целью.
Вот тут:
responseBody = responseBody.Replace("<footer>",То есть в исходной разметке ищется подстрока <footer>, которая дальше заменяется на сгенерированную.
Чтобы передать запрос дальше, надо вызвать await _next(context);, если речь идет об асинхронном методе. Или return _next(context), если речь идет о синхронном.
if (context.Request.Path == "favicon.ico")
{
return _next(context);
}
System.ArgumentException: The path in 'value' must start with '/'.
И когда уже программисты научатся к сообщениям об ошибках прикладывать стектрейсы?..
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 DEBUG http://localhost:57252/ 0
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:57252/index.html?action=test
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17084.406ms 200
Microsoft.AspNetCore.Server.Kestrel:Error: Connection id "0HKVOC28KEBCG": An unhandled exception was thrown by the application.
System.ArgumentException: The path in 'value' must start with '/'.
Parameter name: value
at Microsoft.AspNetCore.Http.PathString..ctor(String value)
at Microsoft.AspNetCore.Http.PathString.op_Implicit(String s)
at WebApplication1.MyMiddleware.<Invoke>d__2.MoveNext() in C:\Users\Макс\Documents\Visual Studio 2015\Projects\WebApplication1\src\WebApplication1\MyMiddleware.cs:line 23
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 39294.2338ms 200
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace WebApplication1
{
public class MyMiddleware
{
RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var act = context.Request.Query["action"];
if (context.Request.Path == "favicon.ico")//Здесь исключение
{
return;// _next(context);
}
var wr = new StreamWriter(context.Response.Body);
var str = ("<html><body>" + wr + "</body></html>").ToCharArray();
wr.Write(str);
}
}
}
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.Extensions.Logging;
namespace WebApplication1
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
//services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//app.UseMvc();
//app.UseStaticFiles();
app.UseMiddleware<MyMiddleware>();
}
}
}
В следующий раз не забывайте спойлеры ставить.
И читайте описание ошибок внимательнее! У вас ошибка не при чтении Path — а при преобразовании строкового литерала в PathString.
ASP.NET 5 Middleware или куда же пропал мой HTTP модуль?