在WCF REST服务中获取原始请求URL

dan*_*iax 13 c# rest web-services

我要在我的WCF rest webservice中检索原始请求URL.现在我的代码看起来像这样:

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

        var url = operationContext.IncomingMessageProperties.Via.OriginalString;
        ...
Run Code Online (Sandbox Code Playgroud)

web.config中

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      <standardEndpoints> 
         <webHttpEndpoint>
             <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

如果我的原始网址是

http://192.168.1.100:8081/test

这段代码返回

HTTP://主机名:8081 /测试

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

注意

我在web.config中找到了关于cutomize"baseAddress"标签的帖子,但是我的扩展名webservice没有特定的端点,我不想添加它.我不知道是否有办法在没有端点的情况下做到这一点.

我发现这篇文章 /sf/answers/414099941/与System.Net.HttpRequestHeader.Host一起播放,但是端口号不起作用!我知道我可以解析提供的URL并进行替换但是......我不认为这是实现此目的的最佳实践.

小智 29

System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.OriginalString;
Run Code Online (Sandbox Code Playgroud)

这给出了原始URI.

  • 没关系......`OperationContext.Current.RequestContext.RequestMessage.Headers.To`给了我我需要的东西. (5认同)
  • 与HttpContext(在另一个答案中引用)相比,使用WebOperationContext的一个优点是它支持更广泛的场景,包括自托管服务.另一方面,HttpContext仅限于aspNetCompatibilityMode和IIS托管. (3认同)
  • 我想使用它,但是`System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.UriTemplateMatch` 是`null` ......这可能是什么原因? (2认同)

bhu*_*ber 5

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

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

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

  • 我认为`HttpContext.Current`只能用于在ASP.NET兼容模式下运行的WCF服务. (8认同)