zoukankan      html  css  js  c++  java
  • asp.net core获取当前请求的完整url

    asp.net core获取当前请求的完整url

    首先需要在控制器项目中使用NuGet引入 Microsoft.AspNetCore.Http.Abstractions包。

    然后有两种获取当前URL的方式。

    方法1,在控制器里面,string displayUrl = HttpContext.Request.GetDisplayUrl();

    方法2,定义一个HttpRequest的扩展类。

    using Microsoft.AspNetCore.Http.Extensions;
    
    namespace demo1.tools
    {
        public static class HttpRequestExtensions
        {
            public static string GetAbsoluteUri(this HttpRequest request)
            {
                return new StringBuilder()
                    .Append(request.Scheme)
                    .Append("://")
                    .Append(request.Host)
                    .Append(request.PathBase)
                    .Append(request.Path)
                    .Append(request.QueryString)
                    .ToString();
            }
        }
    }

    调用方式:

    方法1,直接调用 Request.GetDisplayUrl()方法。
    string displayUrl = HttpContext.Request.GetDisplayUrl();
    方法2 调用扩展方法
    string requestUrl = HttpRequestExtensions.GetAbsoluteUri(HttpContext.Request);

    using demo1.tools;
    using Microsoft.AspNetCore.Http.Extensions;
    
    namespace demo1.xTwoMvc.Controllers
    {
        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                //方法1 直接调用Request.GetDisplayUrl()方法
                string displayUrl = HttpContext.Request.GetDisplayUrl();  
                //方法2 调用扩展方法
                string requestUrl = HttpRequestExtensions.GetAbsoluteUri(HttpContext.Request);
                base.ViewData["displayUrl"] = displayUrl;
                base.ViewData["requestUrl"] = requestUrl; 
                return View();
            }
        }
    }


  • 相关阅读:
    移植nand驱动补缺:make mrproper与make clean以及make distclean,find/grep. makefile
    repo使用
    git使用总结
    notepade++使用
    linux内核源代码、配置与编译
    linux内核介绍
    块设备
    PHP和javascript中url编码解码详解
    python中的类方法、静态方法、对象方法
    webpack+vue中安装使用vue-layer弹窗插件
  • 原文地址:https://www.cnblogs.com/yyee/p/12825802.html
Copyright © 2011-2022 走看看