Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

entity framework - How to pass multiple model as parameter in WEB API

Can anyone please help me to pass multiple models as a parameter to the request's content in WEB API?

I have 2 different Model Student and Employee

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

I have created an API and want to pass both these models as parameters in my action method InsertTestAPI.

[HttpPost]
[Route("TestAPI")]

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

When I pass these models as JSON in the request body, I get the following error from 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)
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"
}

Can anyone please help me?

question from:https://stackoverflow.com/questions/65931310/how-to-pass-multiple-model-as-parameter-in-web-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public class StudentEmployeModel
{
 public Student Students{get;set;}


public Employee Employees{get;set;}
}

Create the StudentEmpendedModel class this way.

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

request this way

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

This way you can send requests as Json


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...