【问题标题】:How to define custom api routes in Azure Mobile Service when using .NET as Back end?使用 .NET 作为后端时,如何在 Azure 移动服务中定义自定义 api 路由?
【发布时间】:2015-07-19 17:57:39
【问题描述】:

尝试了 Table Controller 和 Custom Controller,但无法定义两个接受相同参数和相同 http 方法的函数。例如当声明

public Person GetMemberDetails(int id)
{
   // Some Code
   return person;
}

public Person GetMemberAddress(int id)
{
   // Some Code
   return person;
}

由于这两个函数都使用 GET 请求,并且在构建项目后都具有相同的输入,因此我无法使用它们中的任何一个。当我删除一个或修改一个以使用我能够请求的任何其他请求方法时。

http://<azure-mobile-service-name>/Person/{id}

有没有办法声明两个具有相同签名和相同请求方法的函数?

【问题讨论】:

    标签: asp.net azure azure-mobile-services


    【解决方案1】:

    我花了几个小时试图在 Azure 应用服务中获取多个发布方法(请注意应用服务取代了移动服务,参考:Upgrade your existing .NET Azure Mobile Service to App Service)。

    通用解决方案可以在前面提到的Multiple HttpPost method in Web API controller中找到。但是,对于应用服务,有一条非常重要的评论。 在微软官方示例(参考:Work with the .NET backend server SDK for Azure Mobile Apps)中,默认配置建议为:

    HttpConfiguration config = new HttpConfiguration();
    
    new MobileAppConfiguration()
        .UseDefaultConfiguration()
        .ApplyTo(config);
    

    不幸的是,UseDefaultConfiguration() 方法调用 MapApiControllers(),它定义了标准路由“api/{controller}/{id}”,对 {id} 没有约束。这种路由与“api/{controller}/{action}”不兼容。所以,如果有人想使用多个 post 方法,标准配置应该替换为:

    HttpConfiguration config = new HttpConfiguration();
    
    new MobileAppConfiguration()
        .AddTables(new MobileAppTableConfiguration().MapTableControllers().AddEntityFramework()).AddMobileAppHomeController().AddPushNotifications()
        .ApplyTo(config);
    config.Routes.MapHttpRoute("ActionApi", "api/{controller}/{action}");
    

    当然可以使用“api/{controller}/{action}/{id}”路由,也可以使用可选的{id}。

    我希望我的调查可以为某人节省数小时的紧张情绪。如果来自 Microsoft 的人阅读了这篇文章 - 请在默认示例中稍作评论,或者更好的是,向 UseDefaultConfiguration 添加一个参数来决定是否使用“api/{controller}/{action}”路由。

    【讨论】:

    • 谢谢!我一直在尝试通过大量的谷歌搜索来让它工作 3-4 个小时。你的帖子解决了我的问题。不过请注意:MobileAppTableconfiguration 不应该是 MapTableControllers 而不是 MapApiControllers?
    • 是的,斯特凡,你是对的。我已经在我的帖子中更正了代码。谢谢。
    • 别忘了使用:config.MapHttpAttributeRoutes();否则属性将被忽略...
    【解决方案2】:

    你需要使用Route属性,例如:

     [Route("api/getdetails")]
    public Person GetMemberDetails(int id)
    {
       // Some Code
       return person;
    }
    [Route("api/getaddress")]
    public Person GetMemberAddress(int id)
    {
       // Some Code
       return person;
    }
    

    如果要路由中的id,或者搜索“属性路由”

    【讨论】:

    • 请注意,您需要使用移动服务 APIController 而不是 TableController,因为 TableController 会为您设置一些路由。
    • 请问有没有特殊的方式在移动客户端调用这些自定义路由?
    【解决方案3】:

    根据 RESTful 原则,对于具有一个特定签名的动词,您只能使用一种方法。但是你总是可以修改你的路由并实现它,但你不会坚持使用 REST。在某些情况下,如果情况需要,这样做是可以的。 参考这篇文章Multiple HttpPost method in Web API controller

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2016-06-13
    • 1970-01-01
    相关资源
    最近更新 更多