【发布时间】: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”过滤器包含在其中的方法。
【问题讨论】:
-
您是否需要类似:
Url.Content("~/api/cars/")? -
显然我的 Url 没有 Content() 方法...您从哪个库获取 Url?
-
Razor 中是这样写的。大概你可以写UrlHelper.Content? msdn.microsoft.com/en-us/library/…
-
这段代码在什么上下文中运行,是 ASP.NET MVC 控制器还是 WebForms 页面?在这种情况下,请参阅What's the best method in ASP.NET to obtain the current domain?。
-
此代码在 SignalR 集线器方法中
标签: c# asp.net-web-api