[英]Strongly typed web api route endpoints in mvc
所以我有两个单独的项目(一个Web Api 2和一个MVC),如下图所示:
MVC具有控制器和服务层。 MVC应用程序的服务调用web api控制器。 例如:
await _service.GetGiftCards("/api/GiftCards/ViewAllByUser", email);
Web Api控制器的路由定义如下:
[RoutePrefix("api/giftcards")]
[Route("ViewAllByUser")]
public async Task<List<GiftCard>> GetGiftCardsForUser(string email){}
因此,要在MVC应用程序中定义端点路由,我只需传递上面的“/ api / GiftCards / ViewAllByUser”字符串。
我的问题是,有没有更好的方法来“强类型”定义的Web Api路由的端点,所以我可以做类似的事情:
await _service.GetGiftCards(GiftCardController.ViewAllByUser, email);
我想至少我总是可以将端点字符串存储在静态类中,所以它们至少可以在一个地方更新:
public static class ApiEndpoints(){
public string GetAllGiftCards = "api/GiftCards/ViewAllByUser";
}
但我想知道是否有更好的方法或其他建议。 谢谢!
API路由不应指定操作。 您希望路由成为记录或记录组的逻辑路径。 例如,在您的情况下,路由应如下所示:
GET
api/giftcards/{userID:int:min(1)}
你希望能够基本上走上网址并获得你期望的结果。 在示例路线的情况下,您将获得基于用户ID的礼品卡。 如果您要取消用户ID页面并只需拨打api / giftcards,您就可以获得所有用户的所有礼品卡。 我在这里使用了一个ID,但你会用电子邮件做同样的事情。
请尝试使用'ActionName'属性进行操作,如下所示:
[ActionName("SelectAll")]
public IEnumerable<Customer> Get()
{
...
}
将此操作名称称为:
$("#getdata").click(function () {
var options = {};
options.url = "/api/customer/SelectAll";
options.type = "GET";
...
...
$.ajax(options);
});
注意:'getdata'是控件的id,将触发哪个click事件并从api调用'api method'和getdata
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.