【问题标题】:How to properly compute Web API methods URLs in TypeScript within ASP.NET Core 1.1. solution?如何在 ASP.NET Core 1.1 中正确计算 TypeScript 中的 Web API 方法 URL。解决方案?
【发布时间】:2017-04-22 19:46:02
【问题描述】:

我正在尝试设置 Visual Studio 2017 ASP.NET Core 1.1 解决方案以使用 Angular2 SPA。

我使用以下命令创建了一个示例csproj

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

然后在 Visual Studio 2017 Community Edition 中打开它。

使用 IIS Express 10 运行时,它工作正常(路由、刷新、Web API 调用)。但是,在 IIS 下的 Web 应用程序中部署时,由于路径不包含 Web 应用程序名称,Web API 调用失败:

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 下会失败,因为正确的路径是:

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

在 URL 中硬编码应用程序名称有效,但这不是一个可行的解决方案。

我已更改 _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>

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

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

【问题讨论】:

    标签: asp.net-web-api asp.net-core iis-8 visual-studio-2017 typescript2.0


    【解决方案1】:

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

    您已经正确设置了基本路径(通过&lt;base href="~/"/&gt; 也可以更轻松地设置)。这将确保始终将基本路径用作相对 url 的起点。这也适用于 ajax 调用。所有新浏览器都已经支持&lt;base href=""/&gt;。另请参阅我以前的帖子here

    【讨论】:

    • 是的,它有效。谢谢!我的代码中有两个错误:&lt;base href="@basePath" /&gt; 应该是 &lt;base href="@basePath/" /&gt;&lt;base href="~/"/&gt; 并删除额外的 / 如你提到的。
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 2017-10-30
    • 2019-10-11
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2022-07-04
    相关资源
    最近更新 更多