ASP.NEt MVC using Web API to return a Razor view

前端 未结 3 690
广开言路
广开言路 2020-12-02 17:47

How to make the View returned by the controller and generated by Razor get the data from the api i want to keep the razor engine view and use the api the original mvc cont

相关标签:
3条回答
  • 2020-12-02 18:23

    Read here on how to use the Razor view engine inside your Web API controller. The interesting part is using the RazorEngine NuGet package to do the heavy lifting.

    0 讨论(0)
  • 2020-12-02 18:25

    The basis of the link supplied by twoflower is to have your handlers create and return an instance of a custom IHttpActionResult implementation. A simplified example is shown below:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 18:30

    You could send an HTTP request to your Web API controller from within the ASP.NET MVC controller:

    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);
        }
    }
    

    Also if you can take advantage of the .NET 4.5 async/await it is strongly recommended to do so to avoid blocking calls:

    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 讨论(0)
提交回复
热议问题