我有一個ApiController和一個控制器在同一個ASP.NET項目。我的想法是,我想將REST API公開給第三方,並在我公開的REST API之上構建一個網站。從MVC消費授權WebAPI 2
我想從我的MVC控制器(在ProfileController中)使用REST API(在ProfileApiController中)。兩個控制器都需要進行身份驗證,並且ProfileApiController的響應取決於活動的User.Identity。
我該如何做到這一點?下面
代碼:
namespace Controllers
{
[Authorize]
public class ProfileApiController : ApiController
{
[Route("api/profile/{param}")]
[HttpGet]
public async Task<IHttpActionResult> GetProfile(string param)
{
return this.Ok<IEnumerable<TransferObject>>(/* business logic */);
}
}
[Authorize]
public class ProfileController : Controller
{
public async Task<ActionResult> GetProfile()
{
//Pseudocode -- this is what I'm looking for
var api = (reference_to_profileapicontroller);
api.Authenticate(User.Identity);
var m = api.GetProfile("myparameter");
//End Pseudocode
return View(m):
}
}
}
我已經嘗試過兩種方法:
通過電話HttpClient的
HttpClientHandler h = new HttpClientHandler(); var client = new HttpClient(h); var response = client.GetAsync("http://localhost:4827/api/profile/param/").Result; var m = await response.Content.ReadAsAsync<List<TransferObject>>(); return View(m);
但在這裏,我堅持從控制器傳遞身份到ApiController
調用控制器直接
var pc = DependencyResolver.Current.GetService<ProfileController>(); var r = await pc.GetTenseProfile("param"); var rr = await r.ExecuteAsync(System.Threading.CancellationToken.None); var m = await rr.Content.ReadAsAsync<List<TransferObject>>(); return View(m);
但是這變成一個爛攤子作爲pc.Configuration和pc.Request需要配置。這不應該這麼難嗎?
你可以創建一個業務層,並在兩個控制器中調用它 –
看起來像什麼? –
這是唯一的方法嗎?這對我來說似乎是一種常見的情況? –