.net core2.0获取host的方法

原文: .net core2.0获取host的方法

Example there's an given url: http://localhost:4800/account/login

获取整个url地址:

在页面(cstml)中 

Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(Context.Request);

在 Controller 中

Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(Request);

获取请求的方式(scheme:http/https):http

In asp.net 4.6 -> Request.Url.Scheme

in .net core -> Context.Request.Scheme (cshtml) , in Controller -> Request.Scheme

获取域名(不带端口号)[Get the host]:

In asp.net 4.6 -> Request.Url.Host

in .net core -> Context.Request.Host.Host (cshtml) , in Controller -> Request.Host.Host

获取域名(带端口号)[Get the host]: localhost:4800

In asp.net 4.6 ->

in .net core -> Context.Request.Host.Value (cshtml) , in Controller -> Request.Host.Value

获取路径(Get the path): /account/login

In asp.net 4.6:

In .net core: @Context.Request.Path (cshtml)

获取端口号(Get port): 4800 (if a url contains port)

In asp.net 4.6: Request.Url.Port

In .net core: @Context.Request.Host.Port (cshtml) , in Controller -> Request.Host.Port

通过 urls 配置,详见 Server URLs


  
  
  1. public class Startup
  2. {
  3. public void Configure(IApplicationBuilder app, IConfiguration conf)
  4. {
  5. app.Run( async (context) =>
  6. {
  7. await context.Response.WriteAsync(conf[ "urls"]);
  8. });
  9. }
  10. }

后来参考 Microsoft.AspNetCore.Rewrite 的源代码,写了一个扩展方法实现了。


  
  
  1. namespace Microsoft.AspNetCore.Http
  2. {
  3. public static class HttpRequestExtensions
  4. {
  5. public static string GetAbsoluteUri(this HttpRequest request)
  6. {
  7. return new StringBuilder()
  8. .Append(request.Scheme)
  9. .Append( "://")
  10. .Append(request.Host)
  11. .Append(request.PathBase)
  12. .Append(request.Path)
  13. .Append(request.QueryString)
  14. .ToString();
  15. }
  16. }
  17. }

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12934715.html