从HTTPClient调用时在webapi调用上获取404

本文关键字:调用 获取 webapi HTTPClient | 更新日期: 2023-09-27 17:59:02

所以我继续我的传奇故事来追踪这个奇怪的WebApi问题。

我们的生产环境如下:,2台windows 2012服务器,负载均衡器后面有IIS 8.5。

当我直接访问网站时,http://MyServer/ApiToHit/api/Values?samAccountName=someAccount&成功=真&permissionName=MyPermission

我得到了一个很好的成功字符串。

但是,当在服务器1上使用指向服务器1上的api的httpclient页面时,我会得到一个404错误页面。如果我将链接更改为服务器2,它将完美工作。

HTTP错误404。找不到请求的资源。

HttpClient代码

using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var values = HttpUtility.UrlDecode(string.Format(
                    CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["PathToParameters"].ToString(),
                    "someAccount".ToUpper(CultureInfo.InvariantCulture),
                    true.ToString(),
                    "MyPermission".ToUpper(CultureInfo.InvariantCulture)));
                lblResult.Text = string.Empty;
                var newUrl = new Uri(ConfigurationManager.AppSettings["Url"].ToString() + values);
                // HTTP GET
                var response = await client.GetAsync(newUrl, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
                //var response = await client.GetAsync(values, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
                this.lblResult.Text = await response.Content.ReadAsStringAsync();
            }

这是有问题的api(问题的缩写)

[Authorize]
public class ValuesController : ApiController
{
    public string Get(string samAccountName, bool success, string permissionName)
    {
        var returnValue = "Success";
        return returnValue;
    }
}

路线

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    // Web API routes
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

我们已尝试使用更改web.config

<modules runAllManagedModulesForAllRequests="true"/>

<modules>
  <remove name="UrlRoutingModule-4.0" />
  <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  <!-- any other modules you want to run in MVC e.g. FormsAuthentication, Roles etc. -->
</modules>

从HTTPClient调用时在webapi调用上获取404

我们不得不采取措施来解决这个问题。

1-在IIS中的绑定下,我们在主机名部分为端口80的所有可用ip(在服务器上)添加了服务器名称。