Current URL in ASPCore Middleware?

五迷三道 提交于 2019-12-20 02:47:33

问题


Is there a way I can access the current Requested URL in ASPCore 2.0 Middleware?

Is there something I can Inject?


回答1:


HttpContext object will be passed to the Invoke method of your middleware. You can access the Request property on that.

You can use the GetDisplayUrl extension method or GetEncodedUrl extension method.

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);
}

These 2 extension methods are defined in Microsoft.AspNetCore.Http.Extensions namespace. So make sure you have a using statement to include the namespace

using Microsoft.AspNetCore.Http.Extensions;



回答2:


Your middleware get HttpContext context which has

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

So you may get all needed info in next way:

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

    await next.Invoke();

});


来源:https://stackoverflow.com/questions/45572798/current-url-in-aspcore-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!