【问题标题】:Multiple GET and POST methods in Web API controllerWeb API 控制器中的多个 GET 和 POST 方法
【发布时间】:2014-03-27 10:03:24
【问题描述】:

我已经为这个问题苦苦挣扎了好几天。我有一个需要多个 GET 和 POST 方法的控制器。不知何故,我设法在控制器中实现了多个 GET 方法。当时只有一种 POST 方法。在我介绍了另一种 POST 方法之前,一切都运行良好。每当我使用 ExtJS 从客户端使用 POST 方法时,只会调用第一个 POST 方法。以下是我的控制器中的方法:

[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
}

我还有两个路由配置文件。第一个有如下配置:

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 }
);
}

另一个文件有如下配置:

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 });
}

这是对 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.');
                                    }
                                });

谁能指出错误?或者,在带有路由配置的一侧控制器中具有多个 GET 和 POST 方法的任何示例都会非常有帮助。

【问题讨论】:

  • 你怎么称呼他们?
  • 对于 get 方法,我使用 'localhost/myapp/api/users/userlist/true' 和 localhost/myapp/api/users/alluserlist' 工作正常。对于这两种 POST 方法,我只使用具有不同参数的 'localhost/myapp/api/users'。
  • 但是你怎么称呼他们?您如何在请求中指定它是 POST 还是 GET?
  • 我正在使用 ExtJS。在对 URL 进行 ajax 调用时,您必须指定方法类型。这是一个示例:代理:{类型:'ajax',url:'localhost/myapp/api/users/userlist/true',方法:'GET'}
  • 您如何发送要使用的 POST 方法?

标签: c# asp.net-web-api extjs4 asp.net-web-api-routing


【解决方案1】:

你为什么不对UpdateUser使用PUT方法?

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

更新

您可以使用多个 POST,但您应该使用有效但不 restfulActionNames 或停止使用 复杂类型 作为参数。因为 Web API 在尝试选择最合适的 Action 时会忽略 Complex Types。检查这些:

Multiple actions for the same HttpVerb

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

【讨论】:

  • 我会试一试的。另一方面,我有一个问题,为什么我不能在控制器中使用多个 POST 方法?如果可以,怎么做?
  • 我已经包含了 actionname 属性。还是没有运气。
  • 您是否将操作名称添加到客户端 api POST url 中?
  • 是的。这就是为什么我为每个方法都包含了 actionname 属性。
【解决方案2】:

你可以试试这个

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" }
        );
    }
}

【讨论】:

    【解决方案3】:

    您也可以将 ActionName 用于您的方法

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

    此外,当您调用 post 方法时,您必须在 API 的 URL 中使用 ActionName。 确保您的路由配置在 WebApiConfig 中有 {action}。

    对于 Web API 中的自定义绑定,您可以参考以下链接 https://blogs.msdn.microsoft.com/jmstall/2012/04/16/how-webapi-does-parameter-binding/

    【讨论】:

    • 您没有看到问题。我对每个方法都使用了 actionname 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2012-10-22
    相关资源
    最近更新 更多