【问题标题】:Get host name in webapi method在 webapi 方法中获取主机名
【发布时间】:2017-04-13 06:13:56
【问题描述】:

我想在我的 webapi 方法中获取网站 url。 例如 我的网站名称是 abc.com,我的 api 方法 url 是 xyz.com/getdetails?a=1 现在在我的 webapi 控制器上,我想获取 abc.com url 以从这个方法中识别。

【问题讨论】:

  • 你想要调用你API的客户端IP地址吗?
  • @SyedAliTaqi 我想要客户的域名。
  • 试试this

标签: c# asp.net asp.net-web-api


【解决方案1】:

您将获得一些完整的信息以及托管 api 的端口。但是您需要添加 System.Web 才能使其工作。

HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath.TrimEnd('/');

【讨论】:

    【解决方案2】:

    我相信您需要引用 URL。

    Request.UrlReferrer
    

    【讨论】:

    • 它总是给出空值。
    • 为我工作。我从 jsfiddle 演示向我的 api 发出请求。我的 urlReferrer 回来了:fiddle.jshell.net/_display 你的代码是什么样的?在我看来,您在发出 api 请求之前正在访问该属性。
    【解决方案3】:

    试试这个:

    HttpContext.Current.Request.UserHostName;
    

    HttpContext.Current.Request.UserHostAddress;
    

    别忘了加using System.Web;

    【讨论】:

    • 我试过这个,但它总是给我 webapi 主机地址或主机名
    【解决方案4】:

    如果你不使用 OWIN,那么

    HttpContext.Current.Request.Url.Host
    

    位于System.Web 命名空间中

    如果您正在使用 OWIN 而您使用提供经典 asp.net HttpContextMicrosoft.Owin.Host.SystemWeb nuget 包,您也可以从 OWIN 上下文中获取它,如下所示:

    Request.GetOwinContext().Request.Host.Value
    

    GetOwinContext 扩展函数由 Microsoft.AspNet.WebApi.Owin nuget 包提供。

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多