Calling a ServiceStack service from Razor

2019-05-11 18:47发布

问题:

A bit of an edge case here: I need to call a servicestack service from razor (same website) Right now I'm doing

CheckIfConfiguredResponse aResponse= new JsonServiceClient("http:\\localhost:2000").Get<CheckIfConfiguredResponse>("/CheckIfConfigured"); 

Is that the proper way to go about doing it? Or is there better? Also, How do I eliminate having to specify the web address manually and have it automatically populate the host (since it's the same web site)

Thanks in advance, Will.

回答1:

You never want to make a HTTP call back to yourself just to call a ServiceStack service.

Unlike other frameworks, Services in ServiceStack are simply auto-wired C# types which you can access from the IOC like every other registered IOC dependency. i.e. Inside a Razor View you can simply resolve it and call it directly from the IOC with:

var response = base.Get<CheckIfConfiguredService>().Get(new CheckIfConfigured());

This resolves and calls the service like a normal auto-wired C# dependency, but doesn't inject the current request context. If your service does need it, you can instead use AppHostBase.ResolveService which does, e.g:

var response = AppHostBase
  .ResolveService<CheckIfConfiguredService>(HttpContext.Current)
  .Get(new CheckIfConfigured());