简体   繁体   中英

Use Web Api in a MVC Controller

I must create a Web service and application that will use my web service.

I created Web Api project and I have there this method:

namespace StudentListApi.Controllers
{
    //[Authorize]
    public class ValuesController : ApiController
    {
        StudentContext db = new StudentContext();
        // GET api/values
        public IEnumerable<Student> GetStudents()
        {
            return db.Students;
        }
        //...
    }
}

I need to use this method in controller. My MVC site takes data of students. And takes this data in view:

public class HomeController : Controller
{
    private const string APP_PATH = "http://localhost:2640";

    private Models.StudentListEntities db = new Models.StudentListEntities();

    public ActionResult Index()
    {

        //var students = db.Students.OrderByDescending(x => x.Id);
        using (var client = new HttpClient())
        {
            var students = client.GetAsync(APP_PATH + "/api/value").Result;
            //return students.StatusCode.ToString();
            return View(students);
        }

    }
}

But is doesn't work and I have an error:

The error is in Russian, but I think you can understand from name of exception and that type of item model must be StudentList.Model.Student but i have HttpResponseMessage.

How I can take data from Web Service, transform it in the type "StudentList.Model.Student" and give it to View() ?

Since you are making a webservice call, you will need to deserialize the response from the call.
Kind of Deserialization will be based on the response you have configured in the Api.

And it needs to be done on Result.Content.ReadAsStringAsync() value.

Your mentioned URL is in string. I think you need to use URI based address.

Also, alongwith GetAsync you need to use async and await keywords.

Try below sample-

public class DataSourceController : Controller
{
    HttpClient _client;
    string webapiurl = "http://localhost:56472/api/DataSource";

    public DataSourceController()
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(webapiurl);
        _client.DefaultRequestHeaders.Accept.Clear();
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    }


    //
    // GET: /DataSource/
    public async Task<ActionResult> Index()
    {
        var ResponseMessage = await _client.GetAsync(webapiurl);

        if(ResponseMessage.IsSuccessStatusCode)
        {

            var data = ResponseMessage.Content.ReadAsStringAsync().Result;

            var datasource = JsonConvert.DeserializeObject<List<DataSourceInfo>>(data);
            return View(datasource);

        }

        return View("Error");

    }
}

See if this helps.

using (var client = new HttpClient())
{
     var students = client.GetAsync(APP_PATH + "/api/value").Result;
     //return students.StatusCode.ToString();
     return View(students);
}

your path like that (APP_PATH + "/api/value") but your controller name " Values Controller" edit your ValuesController to ValueController or change your path like that (APP_PATH + "/api/values")

Then check your api (" http://localhost:2640/api/values ") works fine than check your request code in HomeController.

I worked it in console application and use Newtonsoft nuget package

Install-Package Newtonsoft.Json

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("yourRootUrl");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/values");
    if (response.IsSuccessStatusCode)
    {

        var res = Task.Factory.StartNew(() => {
            var data = response.Content.ReadAsStringAsync();
            data.Wait();
            return  JsonConvert.DeserializeObject<List<Student>>(data.Result);
        });
        res.Wait();
        foreach (var s in res.Result)
        {
            Console.WriteLine(s.Name);
        }

    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM