我在初创公司等中为中间件做了一些部分。
所以这是我的班级
public class AcceptQueryMiddleware
{
private const string Realm = "Basic realm=My Sales System";
private readonly RequestDelegate _next;
private static readonly IDictionary<Regex, string> FormatAcceptMap = new Dictionary<Regex, string>();
public AcceptQueryMiddleware(RequestDelegate next)
{
_next = next;
}
public void AcceptQueryHttpModule()
{
RegisterFormatAcceptQuery("csv", "text/csv");
RegisterFormatAcceptQuery("excel", "application/vnd.ms-excel");
RegisterFormatAcceptQuery("nav", "application/navision");
}
private static void RegisterFormatAcceptQuery(string format, string acceptHeader)
{
var regex = new Regex(@"([?]|[&])format=" + format);
FormatAcceptMap.Add(regex, acceptHeader);
}
private static void OnApplicationBeginRequest(object sender, EventArgs eventArgs)
{
var app = sender as HttpApplication;
if (app == null) { return; }
var url = app.Request.RawUrl;
foreach (var format in FormatAcceptMap)
{
if (format.Key.Match(url).Success)
{
app.Request.Headers["Accept"] = format.Value;
break;
}
}
}
public void Dispose()
{
}
}
如何将其转换为Core?绕过它?
特别是.NET Core中不支持的HttpApplication
..
或者您有我可以关注的链接或提示吗?
答案 0 :(得分:0)
您希望将HTTP模块迁移到中间件。请参阅documentation了解具体方法。
在您的情况下,您使用HttpApplication
来访问与请求相关的数据。您正在获取原始网址并添加一些标头。您可以easily在中间件中执行的操作。这是一个例子:
public class AcceptQueryMiddleware
{
private readonly RequestDelegate _next;
public AcceptQueryMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Do your "before" stuff here (use the HttpContext)
await _next.Invoke(context);
// Do your "after" stuff here
}
}
并在app.UseMiddleware<AcceptQueryMiddleware>();
课程中调用Startup
(在Configure
方法中)。