我一直在努力解決這些問題幾天。我有一個需要有多個GET和POST方法的控制器。不知何故,我設法在控制器中實現多個GET方法。那時只有一個POST方法。一切都運行良好,直到我引入了一個更多的POST方法。每當我使用ExtJS從客戶端使用POST方法時,只有第一個POST方法被調用。以下是我的控制器的方法:Web API控制器中的多個GET和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 });
}
這是Ajax調用是如何在API的:
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方法的任何示例都將非常有用。
你怎麼叫他們? –
對於獲取方法,我使用'localhost/myapp/api/users/userlist/true'&localhost/myapp/api/users/alluserlist'。對於這兩種POST方法,我只使用具有不同參數的'localhost/myapp/api/users'。 – user1640256
但你打電話給他們?你如何在請求中指定它是POST還是GET? –