简体   繁体   English

Web API控制器中的多种GET和POST方法

[英]Multiple GET and POST methods in Web API controller

I have been struggling with this problems for days. 我已经为这个问题苦苦挣扎了好几天了。 I have a controller that need to have multiple GET and POST methods. 我有一个控制器,需要具有多个GET和POST方法。 Somehow I managed to achieve multiple GET methods in the controller. 我设法在控制器中实现了多种GET方法。 At that time there was only one POST method. 当时只有一种POST方法。 Everything was running fine until I introduced one more POST method. 一切运行良好,直到我引入了另一种POST方法。 Whenever I use POST method from client side using ExtJS, only the first POST method gets called. 每当我从使用ExtJS的客户端使用POST方法时,都只会调用第一个POST方法。 Here are the methods in my controller: 这是控制器中的方法:

[AllowAnonymous]
[ActionName("userlist")]
[HttpGet]
public List<MyApp.Entity.Models.usermaster> Get(bool isActive)
{
//My code
}

[AllowAnonymous]
[ActionName("alluserlist")]
[HttpGet]
public List<MyApp.Entity.Models.usermaster> Get()
{
//My code
}

[AllowAnonymous]
[ActionName("updateuser")]
[HttpPost]
public string UpdateUser(JObject userData)
{
//My code
}


[AllowAnonymous]
[ActionName("adduser")]
[HttpPost]
public string AddUser(JObject newUserData)
{
//My code
}

I also have two route config files. 我也有两个路由配置文件。 The first one has the following configuration: 第一个具有以下配置:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Another file has the following configuration: 另一个文件具有以下配置:

public static void Register(HttpConfiguration config)
{
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "ControllersWithAction",
routeTemplate: "api/{controller}/{action}");

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}

This is how the ajax call is made to the api: 这是对api进行ajax调用的方式:

Ext.Ajax.request({
     url: 'localhost/myapp/api/users/adduser',
     mode: 'POST',
     params: {
              userName: 'user',
              password: 'password'
             },
     success: function (resp) {
              var respObj = Ext.decode(resp.responseText);
                  if (respObj == 'added') {
                  Ext.Msg.alert('Success', 'User added.');
                  }
                                        else {
                                            Ext.Msg.alert('Error', respObj);
                                        }
                                    },
                                    failure: function (resp) {
                                        Ext.Msg.alert('Error', 'There was an error.');
                                    }
                                });

Can anyone point out the mistake? 谁能指出错误? Alternatively, any example with multiple GET and POST methods in side one controller with route config would be very helpful. 另外,在带有路由配置的一侧控制器中具有多个GET和POST方法的任何示例都将非常有帮助。

why don't you use PUT method for UpdateUser ? 为什么不对UpdateUser使用PUT方法?

[AllowAnonymous]
[HttpPut]
public string UpdateUser(JObject userData)
{
   //My code
}

update : 更新

you can use multiple POST but then you should either use ActionNames that works but is not restful or stop using Complex Types as parameters. 您可以使用多个职位 ,但那么应该使用的作品,但不是宁静 ActionNames或停止使用复杂类型作为参数。 because Web API ignores Complex Types when it tries to select most appropriate Action . 因为Web API在尝试选择最合适的Action时会忽略复杂类型 check these : 检查这些:

Multiple actions for the same HttpVerb 同一HttpVerb的多个动作

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

You could try this 你可以试试这个

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
    }
}

you can use ActionName for your method as well 您也可以将ActionName用于您的方法

[AllowAnonymous]
[HttpPost]
[ActionName("userlist")]
public string UpdateUser(JObject userData)
{
//My code
}


[AllowAnonymous]
[HttpPost]
[ActionName("alluserlist")]
public string AddUser(JObject newUserData)
{
//My code
}

Also, you have to use ActionName in your URL for API, when you call your post method. 另外,调用post方法时,必须在URL中使用ActionName来获取API。 Make sure your route Config have {action} in WebApiConfig. 确保您的路由配置在WebApiConfig中具有{action}。

for custom binding in web API you can refer following link https://blogs.msdn.microsoft.com/jmstall/2012/04/16/how-webapi-does-parameter-binding/ 有关Web API中的自定义绑定,您可以参考以下链接https://blogs.msdn.microsoft.com/jmstall/2012/04/16/how-webapi-does-parameter-binding/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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