Search code examples
c#asp.net-web-apiasp.net-mvc-routingattributerouting

WebApi Attribute Routing for URLs with *.js


OK it's not that funny an ending...

I am trying to emulate a RoR-based service in .Net WebAPI. The Ruby implementation of the service is supposed to return a JSON document from a url of:

http://myserver/api/assessments/{id}.js

Note the .js at the end.

I made a RouteAttribute decoration on my api controller like so:

[Route("~/api/assessments/{id}.js")]
public async Task<HttpResponseMessage> GetAssessment(int id)
{
    . . .
}

...but I'm getting a 404 error. I suspected this might be because the request ended in "js", so after a bit of research I found I should set my RouteCollection.RouteExistingFiles to true... this did not seem to have any effect. I am still getting 404.

Am I right? is the .js ending what is causing the 404? How can I get around this? This is a pure WebApi project, so it's not like I'm using JavaScript in it anyway.


Solution

  • Do you have the following in your Web.config? I recently just setup Routing for a project for Work and this line caused me all sorts of hell because it was not present:

    <configuration>
      ...
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
        ...
        </modules>
      </system.webServer>
    </configuration>
    

    The .js extension may not be getting picked up by the managed modules that do the routing.

    Addendum: Additional data that is within that configuration section and required to make it work:

    <configuration>
      ...
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
          <add name="UrlRoutingModule"
             type="System.Web.Routing.UrlRoutingModule, 
                   System.Web.Routing, Version=3.5.0.0, 
                   Culture=neutral, 
                   PublicKeyToken=31BF3856AD364E35" />
        </modules>
        <handlers>
          <add name="UrlRoutingHandler"
            preCondition="integratedMode"
            verb="*" path="UrlRouting.axd"
            type="System.Web.HttpForbiddenHandler, 
                  System.Web, Version=2.0.0.0, Culture=neutral, 
                  PublicKeyToken=b03f5f7f11d50a3a" />
        </handlers>
        ...
      </system.webServer>
    </configuration>