2014-03-03 3 views
15

뷰어를 컨트롤러에서 반환하고 Razor에서 생성하는 방법은 API에서 데이터를 가져옵니다. 면도기 엔진보기를 유지하고 API를 사용하려는 경우 원본 mvc 지금은 API웹 API를 사용하여 면도기보기를 반환하는 웹 API를 사용하는 MVC

MVC 컨트롤러

public class ProductController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

API를 컨트롤러

public class ProductsController : ApiController 
{ 
    private ApplicationDbContext db = new ApplicationDbContext(); 

    // GET api/Products 
    public IEnumerable<Product> GetProducts() 
    { 
     return db.Products; 
    } 
} 

모의 데이터를 원하는대로 제어 파라미터는 데이터를 뷰를 리턴 델 :

@model IEnumerable<WebApplication2.Models.Product> 

@{ 
ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p> 
@Html.ActionLink("Create New", "Create") 
</p> 
<table class="table"> 
<tr> 
    <th> 
     @Html.DisplayNameFor(model => model.Name) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.Category) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.Price) 
    </th> 
    <th></th> 
</tr> 

@foreach (var item in Model) { 
<tr> 
    <td> 
     @Html.DisplayFor(modelItem => item.Name) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.Category) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.Price) 
    </td> 
    <td> 
     @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | 
     @Html.ActionLink("Details", "Details", new { id=item.Id }) | 
     @Html.ActionLink("Delete", "Delete", new { id=item.Id }) 
    </td> 
</tr> 
} 
</table> 
당신은 ASP.NET MVC 컨트롤러 내에서 웹 API 컨트롤러에 HTTP 요청을 보낼 수

답변

17

: 당신이 활용할 수있는 경우도

public class ProductController : Controller 
{ 
    public ActionResult Index() 
    { 
     var client = new HttpClient(); 
     var response = client.GetAsync("http://yourapi.com/api/products").Result; 
     var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result; 
     return View(products); 
    } 
} 

는 .NET 4.5 비동기/await를 강력하게 차단 호출을 피하기 위해 그렇게하는 것이 좋습니다 :

public class ProductController : Controller 
{ 
    public async Task<ActionResult> Index() 
    { 
     var client = new HttpClient(); 
     var response = await client.GetAsync("http://yourapi.com/api/products"); 
     var products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); 
     return View(products); 
    } 
} 
+0

url/api/products를 사용하여 API를 호출하는 html 클라이언트를 만들었지 만, "http://yourapi.com/api/products ") 여기에 정확히 무엇을 넣어야합니까 ?? – user3353484

+0

제품 목록을 리턴하는 웹 API 엔드 포인트의 URL을 넣어야합니다. –

+0

감사합니다! @ Url.Action에 의해 URL을 바꿀 수 있습니까 ?? – user3353484

12

읽기 here 웹 API 컨트롤러 내부의 면도기보기 엔진을 사용하는 방법. 흥미로운 부분은 무거운 짐을 덜기 위해 RazorEngine NuGet package을 사용하는 것입니다.

+0

유용한 링크를 제공해 주셔서 감사합니다. –

+0

MVC에서 API 컨트롤러로 HTTP 요청을하는 것보다 확실히 대답 할 수 있습니다. 왜 그 대답은 너무 많은 upvotes하지만 성능 pov에서 그것을 할 말도 안돼. – Regfor

0

twoflower에서 제공하는 링크의 기초는 처리기에서 사용자 지정 IHttpActionResult 구현의 인스턴스를 만들고 반환하도록하는 것입니다. 다음은 간단한 예제입니다.

public class TestHttpActionResult : IHttpActionResult 
{ 
    private readonly HttpRequestMessage _request; 
    private readonly string _responseString; 

    public TestHttpActionResult(HttpRequestMessage request, string responseString) 
    { 
     _request = request; 
     _responseString = responseString; 
    } 

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     var response = _request.CreateResponse(HttpStatusCode.Created); 
     response.Content = new StringContent(_responseString); 
     response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); 
     return Task.FromResult(response); 
    } 
} 
관련 문제