我是Servicestack的新手并尝试为我当前的项目实现它。现在我将MVC.NET应用程序部署在一台服务器上 (比如http://server1:8080)和部署在不同服务上的servicestack服务(比如http://server2:9080)。
我已经完成了
https://github.com/ServiceStack/ServiceStack/wiki/Mvc-integration
但我无法理解如何将其更改为从http://server2:9080
拨打服务如何从我的MVC控制器调用服务?
Service code is as following
// APPHOST.cs
public class AppHost : AppHostBase
{
public AppHost() : base("Flight app host",
typeof(flightService).Assembly) { }
public override void Configure(Container container)
{
}
}
//请求DTO
[Route("/flights/","POST")]
[Route("/flights/{departure}/{arrival}","POST")]
public class TravelServiceRequest : IReturn<TravelServiceResponce>
{
public string departure { get; set; }
public string arrival { get; set; }
}
//响应DTO
public class TravelServiceResponce
{
public string departure { get; set; }
public string arrival { get; set; }
public string airline { get; set; }
public decimal fare { get; set; }
public DateTime arrivalTime { get; set; }
public DateTime departureTime { get; set; }
}
// service
public class flightService:Service
{
public object Post(TravelServiceRequest request)
{
var response = new TravelServiceResponce
{
departure =request.departure,
arrival =request.arrival,
airline="jet airways",
fare =677,
arrivalTime =new DateTime(2014,12,12,5,6,2),
departureTime = new DateTime(2014,11,12,5,6,2)
};
return response;
}
}
// Gloable.asax.cs file
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
var appHost = new AppHost();
appHost.Init();
}
}
在我的MVC应用中
public class HomeController : Controller
{
public ActionResult Index()
{
//call service from here
return View();
}
}
我有c#代码来调用此服务,但我不确定这是否是在MVC控制器中使用的最佳方式
var client = new JsonServiceClient("http://server2:9080/");
var responce = client.Post(new TravelServiceRequest
{
departure = departure,
arrival = arrival
});
请帮我解决在MVC中呼叫远程服务的最佳方法。
答案 0 :(得分:2)
如果ServiceStack和MVC没有一起托管在同一个Web应用程序中,那么您只需使用ServiceStack Server DTO和.NET Service Client从任何.NET服务客户端访问ServiceStack服务,例如:
var response = client.Post(new TravelServiceRequest { ... });
共享Server DTO .dll的另一种方法是使用Add ServiceStack Reference提供的VS.NET集成,它允许您从远程URL生成Server DTO。
如果ServiceStack和MVC一起托管在同一个AppDomain中,请参阅ServiceStack Integration with MVC,它允许您的控制器通过继承ServiceStackController
来访问大多数ServiceStack功能。
然后,您可以使用以下命令在MVC控制器中执行ServiceStack服务:
var response = base.Execute(new TravelServiceRequest { ... });
这相当于从IOC解析ServiceStack服务并直接调用它,您可以这样做,例如:
using (var service = base.ResolveService<TravelServices>())
{
var response = service.Post(new TravelServiceRequest { ... });
}