[英]Running Angular and Web API in Visual Studio with IIS Express
I have a Visual Studio 2013 solution with a Web API project and a Web UI project (using Angular).我有一个带有 Web API 项目和 Web UI 项目(使用 Angular)的 Visual Studio 2013 解决方案。 I am using IIS Express.我正在使用 IIS Express。
Is there a way to set these projects up so that the Angular code can call the Web API project without hard-coding in the localhost and port number?有没有办法设置这些项目,以便 Angular 代码可以调用 Web API 项目,而无需在本地主机和端口号中进行硬编码?
return $http.get("http://localhost:1561/api/products")
.then(function (response) {
return response.data;
});
If I hard-code localhost:1561 instead of just using the "/api/products" style I have to manually change the code before deploying to production and change it back to run it during development.如果我硬编码 localhost:1561 而不是仅使用“/api/products”样式,我必须在部署到生产之前手动更改代码,并在开发期间将其更改回运行它。
Is there an easier way?有更容易的方法吗?
Thanks!谢谢!
var rootPath;
if (location.hostname === 'localhost') {
rootPath = 'http://localhost:1561';
} else {
rootPath = 'http://' + location.hostname;
}
return $http.get(rootPath + '/api/products')
.then(function (response) {
return response.data;
});
I actually wrote a simple utility method that returns the absolute URL so in your code you just have to type the relative URL.我实际上编写了一个简单的实用程序方法,它返回绝对 URL,因此在您的代码中您只需要键入相对 URL。 Below is this method which you should be able to call from your JS passing the relative URL (ie /api/products ) or by converting it into a helper extension method...下面是这个方法,您应该能够从您的 JS 中调用它并传递相对 URL(即/api/products )或将其转换为辅助扩展方法...
// Code
public static string ToAbsoluteUrl(string relativeUrl)
{
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (HttpContext.Current == null)
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
From what I understand, it is not possible to do what I was attempting to do.据我所知,不可能做我试图做的事情。 Here are the options:以下是选项:
1) Use IIS on the local machine. 1) 在本地机器上使用 IIS。 That way you can set up the paths/virtual directories as necessary.这样您就可以根据需要设置路径/虚拟目录。 This also makes it easier to call the API from other browsers during debugging.这也使得在调试期间从其他浏览器调用 API 变得更加容易。 Note: This does require that you then run Visual Studio in admin mode from this point forward.注意:这确实需要您从现在开始以管理员模式运行 Visual Studio。
2) Put the two projects into one. 2)将两个项目合二为一。 For me this was not a valid option because I am need to deliver the UI code completely separate from the API code.对我来说,这不是一个有效的选择,因为我需要提供与 API 代码完全分开的 UI 代码。
Hope this helps others trying to work with Angular and Web API.希望这有助于其他尝试使用 Angular 和 Web API 的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.