Can I use Content Negotiation to return a View to browers and JSON to API calls in ASP.NET Core?

后端 未结 3 1478
庸人自扰
庸人自扰 2021-02-07 15:33

I\'ve got a pretty basic controller method that returns a list of Customers. I want it to return the List View when a user browses to it, and return JSON to requests that have <

3条回答
  •  生来不讨喜
    2021-02-07 15:42

    I haven't tried this, but could you just test for that content type in the request and return accordingly:

                var result = customers.Select(c => new { c.Id, c.Name });
                if (Request.Headers["Accept"].Contains("application/json"))
                    return Json(result);
                else
                    return View(result);
    

提交回复
热议问题