Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何重载WebApi方法_Asp.net Mvc_Asp.net Web Api_Asp.net Web Api Routing - Fatal编程技术网

Asp.net mvc 如何重载WebApi方法

Asp.net mvc 如何重载WebApi方法,asp.net-mvc,asp.net-web-api,asp.net-web-api-routing,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; } $('#StateID').change(functi

我是WebApi新手,现在我有两个类似的httpPost方法

[HttpPost]
public List<YellowPages.Person> AddPersonDetails(YellowPages.Person person)
{
  Repository.Repository.personsList.Add(person);
  return Repository.Repository.personsList;
}
 $('#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
[HttpPost]
[路线(“获取相关城市”)]
公共列表获取相关城市
[HttpPost]
[路线(“addPersonDetails”)]
公共列表AddPersonDetails
因此,您的GetRelevantCity理想情况下应该是一个GET方法,而不是一篇文章。我建议您在实际操作中以及在javascript代码中将其更改为HttpGet:

[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)
[HttpGet]//这不是必需的;根据命名约定,默认情况下这将是一个GET请求
[路由(“getRelevantCity/{stateId}”)]
公共列表GetRelevantCity(int stateId)
在$.ajax中,更改
类型:'GET'
并在params中传递stateId,或者作为查询字符串或api/getRelevantCity/123传递stateId,其中123是状态id

是吗? 我完全同意关于GET和POST方法的答案,但您可以使用。它看起来像普通的rest调用,但它可以调用api/Object(123)/GetRelevantCity或api/Object(123)/GetRelevantCity(而不是api/Object/123)等方法(您定义的方法)

您还可以基于请求体()创建自定义约束: 很抱歉以这种方式读取帖子数据

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);
    }
}
公共类类型约束:IHttpRouteConstraint
{
公共布尔匹配(HttpRequestMessage请求、IHttpRoute路由、字符串参数名称、IDictionary值、,
HttpRouteDirection(路由方向)
{
返回IsItCorrect(request.Content.ReadAsStringAsync().Result);
}
}

这是多pust的完整示例(此代码可能不太干净,应该进行重构,但我希望想法非常清楚)

可能重复@CodeCaster我的问题是如何在maphttprote方法中为我的模型和字符串添加约束。可以为int和string添加约束,但是如何为模型添加约束,请帮助我理解。我不确定你的意思。您的意思是希望根据发布的属性名称进行路由吗?然后你需要属性路由,就像在副本中解释的那样。@CodeCaster我有两个post方法,现在一个接受字符串作为参数,另一个接受我的模型作为参数,我如何处理这个场景,谢谢,只需使用属性路由即可(
/YourController/AddPerson
/YourController/GetCity
)。无论如何都应该获取后者。
[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)
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);
    }
}