【问题标题】:Web api routing fails in asp.net MVC 5Web api 路由在 asp.net MVC 5 中失败
【发布时间】:2018-06-26 07:44:06
【问题描述】:

我有一个带有大量控制器和 Web api 的 asp.net MVC 5 项目。问题是当我想访问其中一种 api 方法时,我得到 No HTTP resource was found that match the request URI ... 错误。

我在类似的帖子中尝试了所有解决方案,但我并不幸运。 这是我的 RouteConfig 文件:

public static void Register(HttpConfiguration config)
{
    // Routing configs
    config.MapHttpAttributeRoutes();

    // Files api routs
    config.Routes.MapHttpRoute(
        name: "filesApi_1",
        routeTemplate: "api/{controller}/{action}/{file}",
        defaults: new object[]
        {
            new { controller = "Files", action ="SaveAttachment"}
        }
     );

config.Routes.MapHttpRoute(
    name: "filesApi_2",
    routeTemplate: "api/{controller}/{action}/{fileName}",
    defaults:
        new { controller = "Files", action = "DeleteAttachment" }
    );
}

当我转到 htt://localhost:xxxx/api/Files/DeleteAttachment/file_name 时,我得到了错误。

我的 Global.asax.cs 是:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        GlobalConfiguration.Configure(WebApiConfig.Register); 
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        Mapper.Initialize(c=> c.AddProfile<MappingProfile>());
    }

控制器是:

public class FilesController : ApiController
{
    public void SaveAttachment(HttpPostedFileBase file){}
    public void DeleteAttachment(string fileName){}
}

很奇怪,如果我为 web api 操作添加属性路由,它们会按预期工作。例如:

[Route("api/Files/DeleteAttachment/{fileName}")]
public void DeleteAttachment(string fileName){}

我不想为每个操作都编写 Route,因为我有很多操作,这会使代码变得脆弱。如何修复路由表中的路由?谢谢。

【问题讨论】:

    标签: c# asp.net-web-api routing


    【解决方案1】:

    约定路由遵循您在 webApiConfig 中配置的基于模板的路由,但属性路由更加灵活。我同意您可能不想在每个方法上都写 [Route] 属性,但稍后会提供很大的灵活性。

    在我的一个项目中,根据 UI 开发团队的要求,我可以使用同一个控制器来让不同的路由 API 提供类似的功能。Refer this article

    【讨论】:

      【解决方案2】:

      使用属性[HttpGet][HttpPost] 标记您的 Api 控制器方法,以便路由机制知道何时使用每个方法。

      public class FilesController : ApiController
      {
          [HttpPost]
          public void SaveAttachment(HttpPostedFileBase file){}
          [HttpGet]
          public void DeleteAttachment(string fileName){}
      }
      


      ------------------------------------------ --------------------------------------
      第二个问题可能与您的默认路由值有关:

      config.Routes.MapHttpRoute(
          name: "filesApi_2",
          routeTemplate: "api/{controller}/{action}/{fileName}",
          defaults:
              new { controller = "Files", action = "DeleteAttachment" }
          );
      

      默认路由中缺少fileName参数,修改为:

      config.Routes.MapHttpRoute(
          name: "filesApi_2",
          routeTemplate: "api/{controller}/{action}/{fileName}",
          defaults:
              new { controller = "Files", action = "DeleteAttachment", fileName = "" }
          );
      

      config.Routes.MapHttpRoute(
          name: "filesApi_2",
          routeTemplate: "api/{controller}/{action}/{fileName}",
          defaults:
              new { controller = "Files", action = "DeleteAttachment", fileName = RouteParameter.Optional }
          );
      


      ------------------------------------------ --------------------------------------
      好的,如果它仍然无法正常工作,那是因为 file_name 包含 .。 Web api 路由不喜欢最后一个参数中的点字符。

      将您的 URL 从 http://localhost:58893/api/files/deleteattachment/file.jpg
      更改为
      http://localhost:58893/api/files/deleteattachment/file.jpg/
      ,您应该能够调用请求的方法

      【讨论】:

      • 我根据你的评论用文件名更新了答案
      【解决方案3】:

      您必须检查文件名。如果文件 url 即将到来或文件名中的值包含 '/' 它将拆分路由并创建一个新 url 作为

      htt://localhost:xxxx/api/Files/DeleteAttachment/file_name_before_slash/file_name_after_slash

      它与您的网址不匹配。

      检查代码中文件名部分的值。

      ------------------ 编辑 1 ----------------------- -------------

      问题可能出在文件名“file.jpg”中。文件名中的点 (.) 会导致问题 refer to this link,还有更多类似的问题可用。 Also check this one.

      试试

       <configuration>
           <system.web>
               <httpRuntime relaxedUrlToFileSystemMapping="true"/>
      
                <!-- ... your other settings ... -->
           </system.web>
       </configuration>
      

      【讨论】:

      • 当文件名中没有'/'时,我也无法执行操作。
      • @ehsantoghian 您能否提供有关该错误的更多详细信息。比如完整的错误信息或堆栈跟踪。
      • 完整的错误是:{ "message": "No HTTP resource was found that matches the request URI 'http://localhost:58893/api/files/deleteattachment/file.jpg'.", "messageDetail": "No action was found on the controller 'Files' that matches the request."
      • @ehsantoghian 问题出在文件名“file.jpg”中,文件名中的 (.) 导致问题reffer this link,还有更多类似的问题可用。 Also check this one
      • 我修复了文件名中的点 (.),但为简洁起见没有提及
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多