Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用ASP.NET核心获取绝对URL_C#_Asp.net Core_Url - Fatal编程技术网

C# 使用ASP.NET核心获取绝对URL

C# 使用ASP.NET核心获取绝对URL,c#,asp.net-core,url,C#,Asp.net Core,Url,在MVC 5中,我使用以下扩展方法来生成绝对URL,而不是相对URL: public static class UrlHelperExtensions { public static string AbsoluteAction( this UrlHelper url, string actionName, string controllerName, object routeValues = null) {

在MVC 5中,我使用以下扩展方法来生成绝对URL,而不是相对URL:

public static class UrlHelperExtensions
{
    public static string AbsoluteAction(
        this UrlHelper url,
        string actionName, 
        string controllerName, 
        object routeValues = null)
    {
        string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
        return url.Action(actionName, controllerName, routeValues, scheme);
    }

    public static string AbsoluteContent(
        this UrlHelper url,
        string contentPath)
    {
        return new Uri(url.RequestContext.HttpContext.Request.Url, url.Content(contentPath)).ToString();
    }

    public static string AbsoluteRouteUrl(
        this UrlHelper url,
        string routeName,
        object routeValues = null)
    {
        string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
        return url.RouteUrl(routeName, routeValues, scheme);
    }
}
ASP.NET核心中的等效项是什么

  • UrlHelper.RequestContext
    不再存在
  • 您无法获得
    HttpContext
    ,因为不再存在静态
    HttpContext.Current
    属性
据我所知,您现在需要同时传入
HttpContext
HttpRequest
对象。我说得对吗?有什么方法可以得到当前的请求吗


我的思路是否正确,域现在是否应该是一个简单地附加到相对URL的环境变量?这是一种更好的方法吗?

在一个新的ASP.Net 5 MVC项目中,在控制器操作中,您仍然可以执行
this.Context
this.Context.Request
在请求上看起来不再有Url属性,但子属性(架构、主机等)都直接位于请求对象上

 public IActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();
    }
不管您是否希望使用此。上下文或注入属性是另一个对话。

在RC2和1.0之后,您不再需要向扩展类注入
IHttpContextAccessor
。它可以通过
urlhelper.ActionContext.HttpContext.Request
IUrlHelper
中立即获得。然后,您将按照相同的想法创建一个扩展类,但由于不涉及注入,因此更简单

public static string AbsoluteAction(
    this IUrlHelper url,
    string actionName, 
    string controllerName, 
    object routeValues = null)
{
    string scheme = url.ActionContext.HttpContext.Request.Scheme;
    return url.Action(actionName, controllerName, routeValues, scheme);
}
将如何构建它的细节留给accesor,以防它们对某人有用。您可能还对当前请求的绝对url感兴趣,在这种情况下,请查看答案的末尾


您可以修改扩展类以使用接口来获取。有了上下文后,就可以从
HttpContext.Request
中获取实例,并使用其属性
Scheme
主机
协议
等,如下所示:

string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
例如,您可以要求使用HttpContextAccessor配置类:

public static class UrlHelperExtensions
{        
    private static IHttpContextAccessor HttpContextAccessor;
    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {           
        HttpContextAccessor = httpContextAccessor;  
    }

    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName, 
        string controllerName, 
        object routeValues = null)
    {
        string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
        return url.Action(actionName, controllerName, routeValues, scheme);
    }

    ....
}
您可以在
Startup
类(Startup.cs文件)上执行以下操作:


如果您只是想要一个具有路由注释的方法的Uri,那么下面的代码对我来说很有用

台阶 获取相对URL 注意目标操作的路由名称,使用控制器的属性获取相对URL,如下所示:

var routeUrl = Url.RouteUrl("*Route Name Here*", new { *Route parameters here* });
创建一个绝对URL 创建一个新的Uri 例子
[产生(“应用程序/json”)]
[路线(“api/儿童”)]
公共类子控制器:控制器
{
私有只读应用程序的bContext\u上下文;
公共子控制器(ApplicationDbContext上下文)
{
_上下文=上下文;
}
//获取:api/儿童
[HttpGet]
公共IEnumerable GetChild()
{
return_context.Child;
}
[HttpGet(“URI”)]
公共IEnumerable GetChildUris()
{
在_context.Child中从c返回
选择
新Uri(
$“{Request.Scheme}://{Request.Host}{Url.RouteUrl(“GetChildRoute”,new{id=c.ChildId})}”,
乌里金(绝对);
}
//获取:api/Children/5
[HttpGet(“{id}”,Name=“GetChildRoute”)]
public IActionResult GetChild([FromRoute]int id)
{
如果(!ModelState.IsValid)
{
返回HttpBadRequest(ModelState);
}
Child=\u context.Child.Single(m=>m.ChildId==id);
if(child==null)
{
返回HttpNotFound();
}
返回Ok(儿童);
}
}

您可以获得如下url:

Request.Headers["Referer"]
解释

如果referer HTTP头的格式不正确(这可能发生,因为它通常不在您的控制之下),Request.UrlReferer将抛出一个
System.UriFormatException

至于使用
Request.ServerVariables
,:

Request.ServerVariables集合 ServerVariables集合检索预定环境变量的值和请求头信息

Request.Headers属性

获取HTTP标头的集合

我想我不明白为什么您更喜欢
Request.ServerVariables
而不是
Request.Headers
,因为
Request.ServerVariables
包含所有环境变量和头,其中Request.Headers是一个只包含头的短得多的列表

因此,最好的解决方案是使用
Request.Headers
集合直接读取值。但是,如果要在表单上显示该值,请注意Microsoft关于HTML编码该值的警告。

对于ASP.NET Core 1.0以后的版本 ASP.NET核心积压工作 更新:这不会使ASP.NET核心5


有迹象表明,您可以使用
LinkGenerator
创建绝对URL,而无需提供
HttpContext
(这是
LinkGenerator
的最大缺点,也是为什么
IUrlHelper
的原因,尽管使用下面的解决方案设置更复杂更容易使用)请参阅。

这是anwser by的一个变体,该类被寄生连接到同名的现有.net核心MVC类,因此一切正常

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// <see cref="IUrlHelper"/> extension methods.
    /// </summary>
    public static partial class UrlHelperExtensions
    {
        /// <summary>
        /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
        /// route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="actionName">The name of the action method.</param>
        /// <param name="controllerName">The name of the controller.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteAction(
            this IUrlHelper url,
            string actionName,
            string controllerName,
            object routeValues = null)
        {
            return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
        /// virtual (relative) path to an application absolute path.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="contentPath">The content path.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteContent(
            this IUrlHelper url,
            string contentPath)
        {
            HttpRequest request = url.ActionContext.HttpContext.Request;
            return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified route by using the route name and route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteRouteUrl(
            this IUrlHelper url,
            string routeName,
            object routeValues = null)
        {
            return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }
    }
}
名称空间Microsoft.AspNetCore.Mvc
{
/// 
///扩展方法。
/// 
公共静态部分类UrlHelperExtensions
{
/// 
///使用指定的操作名称、控制器名称和名称生成操作方法的完全限定URL
///路由值。
/// 
///URL帮助程序。
///操作方法的名称。
///控制器的名称。
///路线值。
///绝对URL。
公共静态字符串绝对操作(
此IUrlHelper url,
字符串actionName,
var absUrl = string.Format("{0}://{1}{2}", Request.Scheme,
            Request.Host, routeUrl);
var uri = new Uri(absUrl, UriKind.Absolute)
[Produces("application/json")]
[Route("api/Children")]
public class ChildrenController : Controller
{
    private readonly ApplicationDbContext _context;

    public ChildrenController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: api/Children
    [HttpGet]
    public IEnumerable<Child> GetChild()
    {
        return _context.Child;
    }

    [HttpGet("uris")]
    public IEnumerable<Uri> GetChildUris()
    {
        return from c in _context.Child
               select
                   new Uri(
                       $"{Request.Scheme}://{Request.Host}{Url.RouteUrl("GetChildRoute", new { id = c.ChildId })}",
                       UriKind.Absolute);
    }


    // GET: api/Children/5
    [HttpGet("{id}", Name = "GetChildRoute")]
    public IActionResult GetChild([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return HttpBadRequest(ModelState);
        }

        Child child = _context.Child.Single(m => m.ChildId == id);

        if (child == null)
        {
            return HttpNotFound();
        }

        return Ok(child);
    }
}
Request.Headers["Referer"]
/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static class UrlHelperExtensions
{
    /// <summary>
    /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
    /// route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="actionName">The name of the action method.</param>
    /// <param name="controllerName">The name of the controller.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName,
        string controllerName,
        object routeValues = null)
    {
        return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
    /// virtual (relative) path to an application absolute path.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="contentPath">The content path.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteContent(
        this IUrlHelper url,
        string contentPath)
    {
        HttpRequest request = url.ActionContext.HttpContext.Request;
        return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified route by using the route name and route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="routeName">Name of the route.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteRouteUrl(
        this IUrlHelper url,
        string routeName,
        object routeValues = null)
    {
        return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }
}
services
    .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
    .AddScoped<IUrlHelper>(x => x
        .GetRequiredService<IUrlHelperFactory>()
        .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));
namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// <see cref="IUrlHelper"/> extension methods.
    /// </summary>
    public static partial class UrlHelperExtensions
    {
        /// <summary>
        /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
        /// route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="actionName">The name of the action method.</param>
        /// <param name="controllerName">The name of the controller.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteAction(
            this IUrlHelper url,
            string actionName,
            string controllerName,
            object routeValues = null)
        {
            return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
        /// virtual (relative) path to an application absolute path.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="contentPath">The content path.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteContent(
            this IUrlHelper url,
            string contentPath)
        {
            HttpRequest request = url.ActionContext.HttpContext.Request;
            return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified route by using the route name and route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteRouteUrl(
            this IUrlHelper url,
            string routeName,
            object routeValues = null)
        {
            return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }
    }
}
public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
    var request = httpContextAccessor.HttpContext.Request;

    var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();

    if (parameters != null)
    {
        url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
    }

    return url;
}


private static Dictionary<string, string> ToDictionary(object obj)
{
    var json = JsonConvert.SerializeObject(obj);
    return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });
Url.Action(new UrlActionContext
{
    Protocol = Request.Scheme,
    Host = Request.Host.Value,
    Action = "Action"
})