2016-03-07 2 views
2

У меня есть отчет для отправки по электронной почте пользователю (так как требуется некоторое время для создания.) Я не могу вызвать веб-метод и передать viewmodel.Как я могу передать viewmodel методу webapi с контроллера

Это контроллер WebAPI:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 

namespace RecognitionsMVC.Controllers 
{ 
    public class WebAPIController : ApiController 
    { 
     [ActionName("Post")] 
     public static void GetAllRecognitionsBySupervisorAll([FromUri]ViewModels.AllRecognitionsbyAllSupervisors AllRByAllS) 
     { 
      DataSet ds = Classes.Recognitions.GetAllRecognitionsBySupervisorAll(AllRByAllS.BeginDate, AllRByAllS.EndDate, AllRByAllS.RecognizedOrSubmitted); 
      Classes.DataHelper.SendMeExcelFile(ds, "GetAllRecognitionsBySupervisorAll", AllRByAllS.AuthenticatedUser); 
     } 

    } 
} 

Это вид Модель Я использую:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace RecognitionsMVC.ViewModels 
{ 
    public class AllRecognitionsbyAllSupervisors 
    { 
     public DateTime BeginDate { get; set; } 
     public DateTime EndDate { get; set; } 
     public string AuthenticatedUser { get; set; } 
     public bool RecognizedOrSubmitted { get; set; } 

     public AllRecognitionsbyAllSupervisors(DateTime BeginDate, DateTime EndDate, string AuthenticatedUser, bool RecognizedOrSubmitted) 
     { 
      this.BeginDate = BeginDate; 
      this.EndDate = EndDate; 
      this.AuthenticatedUser = AuthenticatedUser; 
      this.RecognizedOrSubmitted = RecognizedOrSubmitted; 
     } 

    } 

} 

и это контроллер Test Я пытаюсь вызвать контроллер WebAPI и передать вид модели:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace RecognitionsMVC.Controllers 
{ 
    public class TestController : Controller 
    { 
     // GET: Test 
     public ActionResult Index() 
     { 
      DateTime BeginDate = new DateTime(2015, 1, 1); 
      DateTime EndDate = new DateTime(2015, 12, 31); 
      string AuthenticatedUser = "123473306"; 
      bool RecognizedOrSubmitted = true; 

      string VPath = "api/WebAPI/GetAllRecognitionsBySupervisorAll"; 
      ViewModels.AllRecognitionsbyAllSupervisors AllRByAllS = new ViewModels.AllRecognitionsbyAllSupervisors(BeginDate, EndDate, AuthenticatedUser, RecognizedOrSubmitted); 
      return View(VPath, AllRByAllS); 

     } 
    } 
} 

Наконец это является WebApiConfig.cs в папке App_Start:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 

namespace RecognitionsMVC 
{ 
    public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      // TODO: Add any additional configuration code. 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional , action = "DefaultAction"} 
      ); 

      // WebAPI when dealing with JSON & JavaScript! 
      // Setup json serialization to serialize classes to camel (std. Json format) 
      var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; 
      formatter.SerializerSettings.ContractResolver = 
       new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); 

     } 
    } 
} 

Ошибка указывает, что api не может быть найдена и отображается во всех папках вида, а не в контроллере WebAPI. Как я могу вызвать метод WebAPI и передать модель представления?

ответ

1

В вашем контроллере вы можете использовать HttpClient для вызова веб-ави.

public class TestController : Controller 
{ 
    // GET: Test 
    public async Task<ActionResult> Index() 
    { 
     DateTime BeginDate = new DateTime(2015, 1, 1); 
     DateTime EndDate = new DateTime(2015, 12, 31); 
     string AuthenticatedUser = "123473306"; 
     bool RecognizedOrSubmitted = true; 

     string VPath = "api/WebAPI/GetAllRecognitionsBySupervisorAll"; 
     ViewModels.AllRecognitionsbyAllSupervisors AllRByAllS = new ViewModels.AllRecognitionsbyAllSupervisors(BeginDate, EndDate, AuthenticatedUser, RecognizedOrSubmitted); 

     var baseUrl = new Uri("http://localhost:1234/");//Replace with api host address 
     var client = new HttpClient();//Use this to call web api 
     client.BaseAddress = baseUrl; 

     //post viewmodel to web api using this extension method 
     var response = await client.PostAsJsonAsync(VPath, AllRByAllS); 

     return View(); 

    } 
} 

Ваш веб-Api также должен измениться, чтобы получить форму модели тела.

public class WebAPIController : ApiController 
{ 
    [HttpPost] 
    [ActionName("Post")] 
    public static void GetAllRecognitionsBySupervisorAll([FromBody]ViewModels.AllRecognitionsbyAllSupervisors AllRByAllS) 
    { 
     DataSet ds = Classes.Recognitions.GetAllRecognitionsBySupervisorAll(AllRByAllS.BeginDate, AllRByAllS.EndDate, AllRByAllS.RecognizedOrSubmitted); 
     Classes.DataHelper.SendMeExcelFile(ds, "GetAllRecognitionsBySupervisorAll", AllRByAllS.AuthenticatedUser); 
    } 

} 
+0

«GetBaseURL» был неизвестен приложению. (Я нооб, поэтому я не был уверен, как это добавить. Также передается модель представления AllRByAllS, которая не может быть преобразована в System.Net.Http.HttpContent. Я пробовал конвертировать, но не был успешным. эти две проблемы? – pldiguanaman

+0

Я нашел функцию GetBaseURL, которую я добавил, которая, как представляется, разрешает первую проблему. Все еще не уверен в преобразовании ошибки в HttpContent из объекта . – pldiguanaman

+0

'GetBaseURL' был просто методом-заполнителем, который вам нужно реализовать самостоятельно Чтобы получить хост вашего сервиса, вы можете жестко запрограммировать его для тестирования. «PostAsync» - это общий метод расширения для «HttpClient» в пространстве имен «System.Net.Http». – Nkosi

1

Я думаю GetAllRecognitionsBySupervisorAll внутри WebAPIController не разрешается быть статичным. Когда вы пометите его как статичное, оно не будет найдено, поэтому попробуйте удалить «статический».

Смежные вопросы