0

I am trying to set up a Visual Studio 2017 ASP.NET Core 1.1 solution to work with an Angular2 SPA.

I have created a sample csproj using the following commands:

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

and then opened it in Visual Studio 2017 Community Edition.

When running using IIS Express 10, it works fine (routing, refresh, Web API calls). However, when deploying within a Web Application under IIS, Web API calls fails due to path not containing Web application name:

fetchdata.component.ts file defines data fetch as follows:

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

This works fine in IIS Express, as path http://localhost:port/api/SampleData/WeatherForecasts is correct. However, this fails under IIS because the correct path is:

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

Hardcoding application name in URL works, but this is not a viable solution.

I have changed _Layout.cshtml to properly set base (path), but it does not work:

<!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>

If I understood correctly, the path is assumed to be relative to tsconfig.json file which is placed outside wwwroot folder. That would explain why all path from js generated from ts do not take web application folder into account.

Question: How can I dynamically specify URL prefix for calls with TypeScript files?

1 Answer 1

1

You have to use a relative path instead of absolute path. Just remove the / from your http.get(...) calls.

You have already correctly set up the base path (which also works easier by doing <base href="~/"/>). This will make sure that the base path is always used as starting point for relative urls. This also applies to ajax calls. All new browsers already support <base href=""/>. Also see my former post here.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it works. Thank you! I had two mistakes in my code: <base href="@basePath" /> should be <base href="@basePath/" /> or <base href="~/"/> and remove the extra / as you mentioned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.