【问题标题】:Dynamic WebAPI Url动态 WebAPI 网址
【发布时间】:2014-06-11 16:15:05
【问题描述】:

我正在使用以下代码从我的 api 获取数据:

using (var client = new HttpClient())
{
    try
    {
        string url = "http://localhost:58639/api/cars/" + carId + "?includeOwners=true";

        var model = client
            .GetAsync(url)
            .Result
            .Content.ReadAsAsync<Car[]>().Result;
        Car c = model[0];
        newCount = c.Persons.Count;

        /* More Code */
    }
}

在 WebApiConfig 中使用此路由:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

有没有办法动态创建 URL,这样如果站点托管在 localhost 以外的其他地方,它仍然可以工作吗?我曾尝试使用 Url.RouteUrl 和 UrlHelper 执行此操作,但我找不到将“?includeOwners=true”过滤器包含在其中的方法。

【问题讨论】:

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


【解决方案1】:

一种方法是将服务器部分放在配置文件(web.config 等)中,并在构建 url 时从那里读取。

只需在 appSetting 中添加基本 url 部分并使用 ConfigurationManager.AppSettings["NameOfKey"] 读取它

【讨论】:

    【解决方案2】:

    请尝试以下代码:

    string domainName = ((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.ServerVariables["HTTP_HOST"];

    您可以动态加载主机和端口或整个域名。

    【讨论】:

    • 请通过解释您提供的代码的作用来改进您的“试试这个”答案。
    猜你喜欢
    • 2013-11-29
    • 2021-04-27
    • 2013-08-17
    • 2012-03-15
    • 2011-01-10
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多