ASP.NEt MVC使用Web API返回Razor视图

use*_*484 17 html c# asp.net-mvc razor asp.net-web-api

如何使控制器返回并由Razor生成的视图从api获取数据我想保留剃刀引擎视图并使用api原始mvc控制器返回视图,数据作为参数现在我希望数据来自API

MVC控制器

public class ProductController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

Api控制器

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

    // GET api/Products
    public IEnumerable<Product> GetProducts()
    {
        return db.Products;
    }
}
Run Code Online (Sandbox Code Playgroud)

模型:

@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>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 18

您可以从ASP.NET MVC控制器中向Web API控制器发送HTTP请求:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您可以利用.NET 4.5 async/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);
    }
}
Run Code Online (Sandbox Code Playgroud)


two*_*wer 17

请阅读此处了解如何在Web API控制器中使用Razor视图引擎.有趣的是使用RazorEngine NuGet包进行繁重的工作.