【问题标题】:How to pass multiple model as parameter in WEB API如何在WEB API中将多个模型作为参数传递
【发布时间】:2021-01-28 05:07:16
【问题描述】:

谁能帮我将多个模型作为参数传递给 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-framework asp.net-web-api model-view-controller postman webapi


    【解决方案1】:
    public class StudentEmployeModel
    {
     public Student Students{get;set;}
    
    
    public Employee Employees{get;set;}
    }
    

    以这种方式创建 StudentEmpendedModel 类。

    public HttpResponseMessage InsertTestAPI(StudentEmployeModel model)
    {// other logical operations }
    

    以这种方式请求

        { "students":   { "studentId":"0", "studentName":"Mehmet", "branch":"software" } ,
     "employees":
     {"employeeId ":0,"employeeName":"Test","department":"IT"} }
    

    这样你就可以将请求作为 Json 发送

    【讨论】:

    • 嗨,Mehmet,感谢您的宝贵回复,您能否告诉我如何在请求正文中将 StudentEmployeModel 作为 JSON 传递时在 Student 和 Employees 模型中设置值?
    • 我把答案写在评论里了
    【解决方案2】:

    之后你可以在学生类中调用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;}
        }
    

    【讨论】:

    • 谢谢你,Divyanshi 的宝贵答案,你的解决方案也有效,但我可以接受所有人的答案,所以我也赞成你的答案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多