Susheel Rawat
Susheel Rawat

Reputation: 85

How to fix page refresh issue with Angular and MVC?

I am using angular 5 inside MVC 5 using and I am using angular routing inside this. Everything working fine but when there is an angular route URL on the browser address bar and I am doing F5 it's giving the error- The resource cannot be found.

I am sure its because this URL pattern does not match with my MVC routing but it matches with angular routes.

How to solve this?

Upvotes: 0

Views: 363

Answers (2)

peinearydevelopment
peinearydevelopment

Reputation: 11474

Odds are you need to have the UrlRewriter module installed for IIS and then you need to have the following in your web.config at system.webServer/rewrite/rules

<rule name="Angular Routes" stopProcessing="true">
  <match url=".*" />
  <conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
  </conditions>
  <action type="Rewrite" url="/Home/Index?url={UrlEncode:{R:0}}" />
</rule>

The specifics of the rewrite rule though will depend on your app. I'm hooking up my angular root html node in my Home/Index view. If you are doing that differently, you will have to update it to route to where you are expecting it to go.

Angular docs

Upvotes: 0

Robert Tab
Robert Tab

Reputation: 174

It is simple to solve this problem. Do this in your imports modules: RouterModule.forRoot(routes, { useHash: true }). In this case, the Url after the hash is not sended anymore to your server side. For more information go here.

Upvotes: 1

Related Questions