2

我正在尝试配置web api区域以允许我传递可选的格式扩展名。这里是我的RegisterArea方法的代码:如何配置Web Api以从url参数中选择响应格式?

public override void RegisterArea(AreaRegistrationContext context) 
{ 
    context.Routes.MapHttpRoute(
     name: "Api_default", 
     routeTemplate: @"Api/{controller}/{action}/{id}.{ext}", 
     defaults: new 
      { 
       action = "Index", 
       id = RouteParameter.Optional, 
       formatter = RouteParameter.Optional 
      }, 
     constraints: new 
          { 
           id = @"[0-9]+", 
           controller = @"[^\.]+", 
           ext = @"json|xml" 
          } 
    ); 

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
      new UriPathExtensionMapping("json", "application/json") 
     ); 

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
      new UriPathExtensionMapping("xml", "application/xml") 
     ); 

} 

现在,如果我去http://www.example.com/api/countries它工作正常,但是当我尝试http://www.example.com/api/countries.json给我

No type was found that matches the controller named 'countries.json'. 

我在做什么错?

回答

0

发现问题!上面的代码是正确的。但是,我正在使用AttributeRouting,它在我的App_Start文件夹中添加了一个AttributeRoutingHttpConfig.cs,并且搞砸了一些东西。所以,如果你遇到这个问题,请检查!

+0

出于好奇,OP是什么意思? – svallory 2013-05-29 03:29:07

+0

_O_riginal _P_oster – 2013-05-29 22:54:27

相关问题