Asp.net-Mvc
如何重載WebApi方法
我是 WebApi 的新手,現在我有兩個這樣的 httpPost 方法
[HttpPost] public List<YellowPages.Person> AddPersonDetails(YellowPages.Person person) { Repository.Repository.personsList.Add(person); return Repository.Repository.personsList; }第二種方法是
[HttpPost] public List<YellowPages.City> getRelevantCity(string stateID) { return new Repository.YellowPages.City().getCity() .Where(x => x.StateID ==stateID).ToList(); }每當我呼叫 getRelevantCity 方法時,就會呼叫 AddPersonDetails 方法,我相信這與 REST 架構有關。現在我的問題是我該如何處理這種情況。我可以在 WebApiConfig.cs 文件中做些什麼並添加約束嗎?如果是,如何處理我正在使用的模型類型的約束。謝謝你。
更新 1
正如建議的那樣,我已經更改了刪除屬性的方法,如下所示
public List<YellowPages.Person> AddPersonDetails(YellowPages.Person person) { Repository.Repository.personsList.Add(person); return Repository.Repository.personsList; } public List<YellowPages.City> getRelevantCity(string stateID) { return new Repository.YellowPages.City().getCity().Where(x => x.StateID == stateID).ToList(); }我的ajax呼叫是這樣的
$('#StateID').change(function () { $.ajax({ type: 'POST', url: '/api/shoppingCart/getRelevantCity', ContentType: 'application/json', data: { 'stateID': $('#StateID').val() }, dataType: 'json', success: function (returnData) { var grid = ''; $.each(returnData, function (i, d) { grid = grid + createDom(d); }); $('#result').empty().append( grid ); }, error: function (xhr, ajaxOptions, thrownError) { alert('error'); } }); }); $('#btnAjax').click(function (e) { debugger; e.preventDefault(); var d = { 'PersonName': $('#PersonName').val(), 'gender': $('#gender').prop('checked', true).val(), 'StreetAddress': $('#StreetAddress').val(), 'StateID': $("#StateID option:selected").text(), 'Pincode': $('#Pincode').val() }; $.ajax({ type: 'POST', url: '/api/shoppingCart/AddPersonDetails', ContentType: 'application/json', data: d, dataType: 'json', success: function (returnData) { var grid = ''; $.each(returnData, function (i, d) { grid = grid + createDom(d); }); $('#result').empty().append( grid ); }, error: function (xhr, ajaxOptions, thrownError) { alert('error'); } }); });無論我進行哪個 ajax 呼叫,第一個方法都會被呼叫,你能幫我處理一下嗎?
更新 2
我的問題很簡單
假設如果我的 webApi 中有 4 個 GET 方法,那麼我該如何處理 webApi 以便我可以實現所有 4 個 GET 方法
進行屬性路由。在您的 api 配置中,添加
config.MapHttpAttributeRoutes();在你的控制器之上:
[RoutePrefix("api")] public class ShoppingCartController....對於行動:
[HttpPost] [Route("getRelevantCity")] public List<YellowPages.Person> GetRelevantCity [HttpPost] [Route("addPersonDetails")] public List<YellowPages.Person> AddPersonDetails因此,理想情況下,您的 GetRelevantCity 應該是 GET 方法而不是 POST。我建議您將其更改為 HttpGet in action 以及您的 javascript 程式碼:
[HttpGet] //this is not required; as per naming convention this will be a GET request by default [Route("getRelevantCity/{stateId}")] public List<YellowPages.Person> GetRelevantCity(int stateId)在 $.ajax 中,更改
type: 'GET'並傳遞參數中的 stateId 或作為查詢字元串或 api/getRelevantCity/123 ,其中 123 是狀態 id