如何重载WebApi方法

时间:2016-08-28 16:08:45

标签: asp.net-mvc asp.net-web-api asp.net-web-api-routing

我是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方法

2 个答案:

答案 0 :(得分:15)

转到属性路由。在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,以及你的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'并传递params中的stateId或查询字符串或api / getRelevantCity / 123,其中123是状态ID

答案 1 :(得分:0)

your case吗? 我完全同意有关GET和POST方法的答案,但您可以使用OdataController。它看起来像常见的休息调用,但它可以调用方法(你定义的),如api / Object(123)/ GetRelevantCity或api / Object(123)/ getRelevantCity(但不是api / Object / 123)

您还可以根据请求主体(an example of the constraint)创建自定义约束: 很抱歉这种阅读帖子数据的方式 ...

public class TypeConstraint: IHttpRouteConstraint
{

    public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values,
        HttpRouteDirection routeDirection)
    {
        return IsItCorrect(request.Content.ReadAsStringAsync().Result);
    }
}

this way of reading the requestMessage 而且there是多个pust的完整示例(这段代码可能不那么干净,应该重构,但我希望这个想法很清楚)

相关问题