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

后端 未结 3 1479
庸人自扰
庸人自扰 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:58

    I think this is a reasonable use case as it would simplify creating APIs that return both HTML and JSON/XML/etc from a single controller. This would allow for progressive enhancement, as well as several other benefits, though it might not work well in cases where the API and Mvc behavior needs to be drastically different.

    I have done this with a custom filter, with some caveats below:

    public class ViewIfAcceptHtmlAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.HttpContext.Request.Headers["Accept"].ToString().Contains("text/html"))
            {
                var originalResult = context.Result as ObjectResult;
                var controller = context.Controller as Controller;
                if(originalResult != null && controller != null)
                {
                    var model = originalResult.Value;
                    var newResult = controller.View(model);
                    newResult.StatusCode = originalResult.StatusCode;
                    context.Result = newResult;
                }
            }
        }
    
        public void OnActionExecuting(ActionExecutingContext context)
        {
    
        }
    }
    

    which can be added to a controller or action:

    [ViewIfAcceptHtml]
    [Route("/foo/")]
    public IActionResult Get(){ 
            return Ok(new Foo());
    }
    

    or registered globally in Startup.cs

    services.AddMvc(x=>
    { 
       x.Filters.Add(new ViewIfAcceptHtmlAttribute());
    });
    

    This works for my use case and accomplishes the goal of supporting text/html and application/json from the same controller. I suspect isn't the "best" approach as it side-steps the custom formatters. Ideally (in my mind), this code would just be another Formatter like Xml and Json, but that outputs Html using the View rendering engine. That interface is a little more involved, though, and this was the simplest thing that works for now.

提交回复
热议问题