首页 > 解决方案 > 如何在WEB API中将多个模型作为参数传递

问题描述

谁能帮我将多个模型作为参数传递给WEB API中的请求内容?

我有 2 个不同的模范学生和员工

public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public string Branch { get; set; }
    }

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Department { get; set; }
    }

我创建了一个 API,并希望在我的操作方法InsertTestAPI中将这两个模型作为参数传递。

[HttpPost]
[Route("TestAPI")]

public HttpResponseMessage InsertTestAPI(Student modelStudent, Employee modelEmployee)
{
    // other logical operations
}

当我在请求正文中将这些模型作为 JSON 传递时,我从 Postman 收到以下错误。

{
    "$id": "1",
    "Message": "An error has occurred.",
    "ExceptionMessage": "Can't bind multiple parameters ('modelStudent' and 'modelEmployee') to the request's content.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": "   at System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"
}

谁能帮帮我吗?

标签: entity-frameworkasp.net-web-apimodel-view-controllerpostmanwebapi

解决方案


之后你可以在学生类中调用Empolyee类。然后你可以在api中调用多个模型调用

public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public string Branch { get; set; }
        public Employee EmpData {get;set;}
    }

推荐阅读