Asp.net-Core

ASPCore 中間件中的目前 URL?

  • January 24, 2018

有沒有辦法可以在 ASPCore 2.0 中間件中訪問目前請求的 URL?

有什麼我可以注射的嗎?

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

這 2 個擴展方法是在Microsoft.AspNetCore.Http.Extensions命名空間中定義的。因此,請確保您有一個 using 語句來包含命名空間

using Microsoft.AspNetCore.Http.Extensions;

引用自:https://stackoverflow.com/questions/45572798