从ASP.NET MVC向Web Api发送数据

时间:2016-06-09 15:55:58

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

在Web Api中,我有一个简单的方法,它采用模型Student

// POST api/values
[HttpPost]
public void CreateStudent([FromBody]Student student)
{
    db.Students.Add(student);
    db.SaveChanges();
}

我的MVC应用程序的方法:

public void Form(string Name, string Surname, string Qualification, string Specialty, double Rating)
{
    Student student = new Student
    {
        Name = Name,
        Surname = Surname,
        Qualification = Qualification,
        Specialty = Specialty,
        Rating = Rating
    };

    //Here I must send student object to Web Api with ulr "http://localhost:2640/api/values"
}

我想从我的MVC应用程序对象Student发送到Web Api,但我不知道如何做到这一点。我必须做什么?

1 个答案:

答案 0 :(得分:1)

假设这样的Web API控制器:

public class StudentsController : ApiController {
    // POST api/students
    [HttpPost]
    public IHttpActionResult Post(Student student) {
        db.Students.Add(student);
        db.SaveChanges();
        return Ok();
    }
}

位于以下终点

http://localhost:2640/api/students

您可以使用HttpClient与MVC控制器中的WebApi进行通信

[HttpPost]
public async Task<ActionResult> Form(string Name, string Surname, string Qualification, string Specialty, double Rating) {

    Student student = new Student {
        Name = Name,
        Surname = Surname,
        Qualification = Qualification,
        Specialty = Specialty,
        Rating = Rating
    };

    // Here I must send student object to Web Api
    // URL: "http://localhost:2640/api/students"
    var client = new HttpClient();
    car endpoint = "http://localhost:2640/api/students";
    var response = await client.PostAsJsonAsync(endpoint, student);
    if(response.IsSuccessStatusCode) {
        return RedirectToAction("Index");
    }
    return View(student);
}