ASPCore中间件中的当前URL?

时间:2017-08-08 15:49:12

标签: asp.net-core asp.net-core-mvc url-routing asp.net-mvc-routing

有没有办法可以访问ASPCore 2.0中间件中当前的请求URL?

我可以注射吗?

2 个答案:

答案 0 :(得分:3)

HttpContext对象将传递给中间件的Invoke方法。您可以访问该Request属性。

您可以使用GetDisplayUrl扩展方法或GetEncodedUrl扩展方法。

public Task Invoke(HttpContext context)
{
    var url1 =context.Request.GetDisplayUrl();
    var url2  = context.Request.GetEncodedUrl();       


    // Call the next delegate/middleware in the pipeline
    return this._next(context);
}

这两个扩展方法在Microsoft.AspNetCore.Http.Extensions命名空间中定义。因此,请确保使用using语句来包含命名空间

using Microsoft.AspNetCore.Http.Extensions;

答案 1 :(得分:2)

您的中间件获得HttpContext context

//
// Summary:
//     /// Gets the Microsoft.AspNetCore.Http.HttpRequest object for this request. ///
public abstract HttpRequest Request { get; }

所以你可以通过下一个方式得到所有需要的信息:

app.Use(async (context, next) =>
{
    //context.Request.Path
    //context.Request.QueryString
    ...

    await next.Invoke();

});