【问题标题】:Unable to set RequestUri of HttpResponseMessage in Web Api Controller无法在 Web Api 控制器中设置 HttpResponseMessage 的 RequestUri
【发布时间】:2019-05-22 17:24:44
【问题描述】:

我正在使用 HttpClient 调用 2 个 API(一个是原始的,一个是模拟的)。

因此,如果 API 调用的 URL 是 https://something.com/abc/xyz,当我在响应中 POST 到此 URL 时,RequestMessage.RequestUri 具有特定值,即 https://something.com/mno/eee?key=asdad

为了复制这种行为,我设置了一个 web api 控制器 -

public class JqPay2Controller : ApiController
{
    [HttpPost]
    [ActionName("donotcare")]
    public HttpResponseMessage DoNotCare()
    {
        var uri = new Uri("https://localhost:3232/mno/eee?key=asdad");
        var contentStr = $"donotcare";
        var res = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(contentStr),
            RequestMessage = new HttpRequestMessage(HttpMethod.Post, uri)
        };
        return res;
    }
}

我的应用程序将以模拟模式调用,我希望在 RequestMessage.RequestUri 属性中看到相同的值。

但我没有看到它,而是在我希望看到https://localhost:3232/mno/eee?key=asdad 时看到了https://something.com/abc/xyz

我不确定这是如何工作的?我在这里做错了什么?

【问题讨论】:

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


    【解决方案1】:

    试试这个代码...

    [HttpPost]
    [ActionName("donotcare")]
    public async Task<HttpResponseMessage> DoNotCare()
    {
        using(HttpClient client = new HttpClient())
        {
           client.BaseAddress = new Uri("http://localhost:3232/"); 
    
           var request = new HttpRequestMessage
             (HttpMethod.Post, "abc/xyz");  // or "mno/eee?key=asdad"
    
           HttpResponseMessage response = await client.SendAsync(request);
    
           return response;
        }
    }
    

    您的代码库中的某处是否有带有路由 ["abc/xyz"] 的 API 端点?还是您实际上是在尝试使用实时外部 api?如果是这样,请将 client.BaseAddress 更改为“https://something.com/api”。此外,在 HttpMethod.Post 之后,将“abc/xyz”更改为它们的实际终点。例如。

    [HttpPost, Route("abc/xyz")]
    public string DoNotCareEndPoint()
    {
        return "https://localhost:3232/mno/eee?key=asdad";
    }
    

    让我知道这会返回什么,我可以尝试进一步帮助您。

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2017-06-28
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多