C# 在 WCF REST 服务中获取原始请求 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9110397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:59:57  来源:igfitidea点击:

Get original request url in WCF REST service

c#web-servicesrest

提问by danyolgiax

I've to retrieve the orginal request url in my WCF rest webservice. Now my code looks like this:

我必须在我的 WCF 休息网络服务中检索原始请求 url。现在我的代码如下所示:

public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        base.CheckAccessCore(operationContext);

        var url = operationContext.IncomingMessageProperties.Via.OriginalString;
        ...

web.config

网页配置

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      <standardEndpoints> 
         <webHttpEndpoint>
             <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

if my original url is

如果我的原始网址是

http://192.168.1.100:8081/test

http://192.168.1.100:8081/test

this code return

此代码返回

http://hostname:8081/test

http://主机名:8081/test

is there a way to retrieve the exact original request url?

有没有办法检索准确的原始请求网址?

Note

笔记

I found posts talking about cutomize "baseAddress" tag in web.config but I've no specific endpoint fom my extensionles webservice and I don't want to add it. I don't know if there is a way to do it without endpoint.

我在 web.config 中发现了关于 cutomize “baseAddress” 标签的帖子,但我的扩展 web 服务没有特定的端点,我不想添加它。我不知道是否有没有端点的方法。

I found this post https://stackoverflow.com/a/5915713/735864plays with System.Net.HttpRequestHeader.Host but with port number it doesn't works! I know I can parse provided url and do a Replace but... I don't think this is the best practice to achieve this.

我发现这篇文章 https://stackoverflow.com/a/5915713/735864与 System.Net.HttpRequestHeader.Host 一起玩,但端口号不起作用!我知道我可以解析提供的 url 并进行替换,但是......我认为这不是实现这一目标的最佳实践。

采纳答案by Karthik D V

System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.OriginalString;

This gives the original URI.

这给出了原始 URI。

回答by bhuber

Short answer: var url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;

简短的回答: var url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;

Long answer: See How to get the URL of the current page in C#.

长答案:请参阅如何在 C# 中获取当前页面的 URL

Warning: This only works if you enable aspNetCompatibilityEnabledin web.config file.

警告:这仅在您在 web.config 文件中启用aspNetCompatibilityEnabled时才有效。