如何在ASP.NET Core 1.1中正确计算TypeScript中的Web API方法URL。解?

问题描述:

我正在尝试设置Visual Studio 2017 ASP.NET Core 1.1解决方案以与Angular2 SPA一起使用。如何在ASP.NET Core 1.1中正确计算TypeScript中的Web API方法URL。解?

我曾尝试使用下面的命令创建了一个示例csproj

npm install -g yo generator-aspnetcore-spa 
yo aspnetcore-spa 

,然后在Visual Studio 2017年社区版打开了它。

使用IIS Express 10运行时,它工作正常(路由,刷新,Web API调用)。然而,在IIS Web应用程序中部署时,网络API调用失败,因为路径不包含Web应用程序名称:

fetchdata.component.ts文件定义取数据如下:

constructor(http: Http) { 
    http.get('/api/SampleData/WeatherForecasts').subscribe(result => { 
     this.forecasts = result.json() as WeatherForecast[]; 
    }); 
} 

这工作正常在IIS Express中,路径为http://localhost:port/api/SampleData/WeatherForecasts是正确的。然而,这种失败在IIS下,因为正确的路径是:在URL

http://localhost:port/ApplicationName/api/SampleData/WeatherForecasts 

硬编码的应用程序名称的作品,但这不是一个可行的解决方案。

我已经改变_Layout.cshtml正确设置基座(路径),但它不工作:

<!DOCTYPE html> 
@{ 
    string basePath = Url.Content("~"); 
} 
<html> 
    <head> 
     <meta charset="utf-8" /> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
     <title>@ViewData["Title"] - WebApplicationBasic</title> 
     <base href="@basePath" /> 
     <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" /> 
    </head> 
    <body> 
     Base path: @basePath 

     @RenderBody() 

     @RenderSection("scripts", required: false) 
    </body> 
</html> 

如果我正确理解,路径被假定为相对于tsconfig.json文件被放置外wwwroot文件夹。这可以解释为什么从ts生成的js的所有路径都不考虑web应用程序文件夹。

问题:如何为使用TypeScript文件的调用动态指定URL前缀?

您必须使用相对路径而不是绝对路径。请从http.get(...)呼叫中删除/

您已经正确设置了基本路径(通过执行<base href="~/"/>也可以更容易)。这将确保基本路径始终用作相对URL的起点。这也适用于ajax调用。所有新的浏览器已经支持<base href=""/>。另请参阅我以前的帖子here

+0

是的,它的工作原理。谢谢!我的代码中有两个错误:''应该是'或''你提到的额外'/'。 – Alexei