2015-07-19 71 views
4

尝试了表控制器和自定义控制器,但无法使用相同的http方法定义接受相同参数的两个函数。声明如何在使用.NET作为后端时在Azure Mobile Service中定义自定义api路由?

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} 

有什么办法可以用相同的签名和相同的请求方法声明两个函数吗?

回答

3

您需要使用路由属性,如:

[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

+0

还要注意,您需要使用Mobile Services APIController而不是TableController,因为TableController为你设置了一些路由。 –

1

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

+0

你能链接到一些权威性的文件,证实REST不允许控制器上有多个GET? OP的问题是单个HTTP GET(路由)不明确,所以Web API处于错误状态。 – Sentinel

+0

请参阅以下网址:http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html https://github.com/flask-restful/flask-restful/issues/114 http://salesforce.stackexchange .com/questions/5693/can-we-create-multiple-http-methods-rest-annotations-of-the-same-type-in​​-a-si – Aravind

4

我已经花了几个小时试图在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/{控制器} /(编号)”对{id}没有限制。这种路由与“api/{controller}/{action}”不兼容。所以,如果有人想使用多个岗位的方法,标准配置应改为:

HttpConfiguration config = new HttpConfiguration(); 

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

当然是可以使用“API/{控制器}/{行动}/{ID}”的路线,而不是,也可选{id}。

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

+1

谢谢!我一直试图通过大量的谷歌搜索让它工作3-4个小时。你的帖子解决了我的问题。但请注意:不应该将MapTableControllers用于MobileAppTable配置,而不适用于MapApiControllers? –

+0

是的Stefan,你说得对。我在我的帖子中更正了代码。谢谢。 –

+0

不要忘记使用:config.MapHttpAttributeRoutes(); 否则属性将被忽略... – Inna