我可以使用内容协商将视图返回到ASP.NET核心中的浏览器和JSON到API调用吗?

Jam*_*ney 12 c# asp.net-mvc asp.net-core

我有一个非常基本的控制器方法,它返回一个客户列表.我希望它在用户浏览时返回列表视图,并将JSON返回给application/jsonAccept标头中的请求.

这可能在ASP.NET Core MVC 1.0中吗?

我试过这个:

    [HttpGet("")]
    public async Task<IActionResult> List(int page = 1, int count = 20)
    {
        var customers = await _customerService.GetCustomers(page, count);

        return Ok(customers.Select(c => new { c.Id, c.Name }));
    }
Run Code Online (Sandbox Code Playgroud)

但是,默认情况下返回JSON,即使它不在Accept列表中.如果我在浏览器中点击"/ customers",我会得到JSON输出,而不是我的视图.

我以为我可能需要编写一个处理的OutputFormatter text/html,但我无法弄清楚如何View()从一个方法调用该方法OutputFormatter,因为这些方法已经打开Controller,我需要知道我想要渲染的View的名称.

有没有我可以调用的方法或属性来检查MVC是否能够找到OutputFormatter要呈现的内容?类似于以下内容:

[HttpGet("")]
public async Task<IActionResult> List(int page = 1, int count = 20)
{
    var customers = await _customerService.GetCustomers(page, count);
    if(Response.WillUseContentNegotiation)
    {
        return Ok(customers.Select(c => new { c.Id, c.Name }));
    }
    else
    {
        return View(customers.Select(c => new { c.Id, c.Name }));
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*est 3

我还没有尝试过这个,但是您可以测试请求中的内容类型并相应地返回:

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