如何使用多个HttpPost操作实现Web API控制器(mvc 4)?

时间:2016-03-09 11:18:35

标签: c# asp.net-mvc-4 asp.net-web-api routes

如何使用多个[HttpPost]操作在MVC 4中实现Web API?

不知何故,它不允许这样做。

以下是我的代码:

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配置:

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

我在Web API2中检查了Route属性可以解决此问题。但是根据客户端的限制,我们必须使用mvc4。 MVC 4不支持Route属性。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

在你的startUp类配置属性路由。

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