简体   繁体   中英

Strongly typed web api route endpoints in mvc

So I have two separate projects (one Web Api 2 and one MVC) like this diagram: 在此输入图像描述

The MVC has controllers and a service layer. The services from the MVC app call to the web api controllers. For example:

await _service.GetGiftCards("/api/GiftCards/ViewAllByUser", email);

The Web Api controllers have their routes defined like so:

[RoutePrefix("api/giftcards")]
[Route("ViewAllByUser")]
    public async Task<List<GiftCard>> GetGiftCardsForUser(string email){}

So to define the endpoint route in the MVC app I simply pass a string like "/api/GiftCards/ViewAllByUser" above.

My question is, is there a better way to sort of "strongly type" the endpoints of the Web Api routes that are defined so I can do something like?:

await _service.GetGiftCards(GiftCardController.ViewAllByUser, email);

I guess at a minimum I could always just store the endpoint strings in a static class like so, so they at least can all be updated in one place:

public static class ApiEndpoints(){
     public string GetAllGiftCards = "api/GiftCards/ViewAllByUser";
}

but I'm looking to know if there are better ways or other suggestions. Thanks!

API routes shouldn't specify actions. You want your routes to be logical paths to a record or group of records. Example, in your case the route should look something like this:

GET
api/giftcards/{userID:int:min(1)}

You want to be able to walk up the url basically and get what you would expect. In the case of the example route you would get gift cards based on the user id. If you were to take off the user id page and just call api/giftcards you would expect to get all gift cards by all users. I'm using an ID here but you would do the same with email.

Pleas try with 'ActionName' Attribute on action like this :

 [ActionName("SelectAll")]
        public IEnumerable<Customer> Get()
        {
       ...
        }

calling this action name like:

$("#getdata").click(function () {
  var options = {};
  options.url = "/api/customer/SelectAll";
  options.type = "GET";
  ...
  ...
  $.ajax(options);
});

note: 'getdata' is id of control which click event will be fired and calling 'api method' and getdata from api

Here's a library that may be what you're looking for.

Although I like static strings so you don't always have to show future developers on your team how to use said library when updates are needed on the clients.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM