-->

Routing of file-like names in Asp.NET WebApi

2019-05-11 17:23发布

问题:

Is it possible to add a route in the ASP.NET Web API routing configuration that allows handling URLs that look a bit like file names?

I tried adding the following entry in WebApiConfig.Register(), but that didn't work (using URI api/foo/0de7ebfa-3a55-456a-bfb9-b658165df5f8/bar.group.json):

config.Routes.MapHttpRoute(
  name: "ContextGroupFile",
  routeTemplate: "api/foo/{id}/{filetag}.group.json",
  defaults: new { controller = "foo", action = "getgroup"}
  );

The following did work though (it called FooController.GetGroup(id,filetag) as expected) (using URI api/foo/0de7ebfa-3a55-456a-bfb9-b658165df5f8/group/bar):

config.Routes.MapHttpRoute(
  name: "ContextGroupFile",
  routeTemplate: "api/foo/{id}/group/{filetag}",
  defaults: new { controller = "foo", action = "getgroup"}
  );

The failed case returns an IIS error (404 - file not found) that looks like it was created by something outside my application. The error page (generated by IIS Express) contained the following error details:

Module = IIS Web Core
Notification = MapRequestHandler
Handler = StaticFile
Error Code = 0x80070002

I guess that means something called a "StaticFile Handler" got its hands on the request before it reached my code. The big question is: is there a way to prevent that?

回答1:

Can you try after having the following settings:

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


回答2:

Replace the handler path filter. Usualy look like this:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Try with 'path="*"'

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />