How to implement Web API in MVC 4 with multiple [HttpPost]
actions?
Somehow it is not allowing to do so.
Following is my code :
public class DataOperationController : ApiController
{
DataOperationManager dalManager = new DataOperationManager();
[HttpPost]
public User AddUser(User user)
{
User newUser = new NBFTestModels.Models.User();
newUser = dalManager.AddUser(user);
return newUser;
}
[HttpPost]
public Device AddDevice(Device device)
{
Device newDevice = new NBFTestModels.Models.Device();
newDevice = dalManager.AddDevice(device);
return newDevice;
}
}
WebAPI Config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}"
);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.EnableSystemDiagnosticsTracing();
}
}
I checked in Web API2 there is Route
attribute which resolves this issue. But as per the client limitations we have to user mvc4. MVC 4 does not support Route attribute. Any suggestions ?
In your startUp class configure attribute routing.
//in your startup class
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
var configuration = new HttpConfiguration();
//for route attributes on controllers
configuration.MapHttpAttributeRoutes();
}
public class DataOperationController : ApiController
{
DataOperationManager dalManager = new DataOperationManager();
[HttpPost, Route("api/users/add")]
public User AddUser(User user)
{
User newUser = new NBFTestModels.Models.User();
newUser = dalManager.AddUser(user);
return newUser;
}
[HttpPost, Route("api/devices/add")]
public Device AddDevice(Device device)
{
Device newDevice = new NBFTestModels.Models.Device();
newDevice = dalManager.AddDevice(device);
return newDevice;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.