How do I change the root path of a ASP.Net WebAPI application?

I am trying create a single page web app combining both ASP.NET WebAPI and the Yeoman Angluarjs generator. Currently I have a project structure as laid out below

|-- yeomanAngularApp
|-- app
|-- dist
|-- scripts
|-- index.html
|-- etc...
|-- WebApiApp
|-- App_Start
|-- bin
|-- Content
|-- Controllers
|-- Models
|-- WebApiApp.csproj
|-- dist
|-- scripts
|-- index.html

When I want to build the app distribution, I copy the dist folder in the yeomanAngularApp into the WebApiApp replacing the dist folder in there.

Now this is all very easy to do. What I really then want to do is to tell the WebApiApp not to use WebApiApp as the root of the project, but use WebApiAppdist. This means instead of going to http://localhost/dist/index.html, I could go to http://localhost/index.html even though index.html is in the dist folder. On top of this I would also like my WebAPI routing for the controllers to play nicely too.

I’ve been searching for a while and I can’t seem to find an answer. The best I can come up with, is using URL rewriting, which to me doesn’t feel right.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

URL rewriting is exactly what you want, with a condition block to test if the file exists. The content under your dist directory is static (i.e. lives on the file system) but the WebApiApp routes are dynamic. So you simply need to test if the route matches a file that exists in the dist directory or not, if not simply let .NET handle the route. Adding the following to your Web.config file within the <system.webServer> section should do the trick:

<rewrite>
  <rules>
  <rule name="static dist files" stopProcessing="true">
    <match url="^(.+)$" />
    <conditions>
      <add input="{APPL_PHYSICAL_PATH}dist{R:1}" matchType="IsFile" />
    </conditions>
    <action type="Rewrite" url="/dist/{R:1}" />
  </rule>
    <rule name="index.html as document root" stopProcessing="true">
      <match url="^$" />
      <action type="Rewrite" url="/dist/index.html" />
    </rule>
  </rules>
</rewrite>

The second rule is optional but it means a request for the root of your site will still serve the index.html file from the dist directory, effectively making the root of the project WebApiAppdist but still allowing all WebAPI routing.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x