Skip to content

ContentHttpResult(string? content, string? contentType, int? statusCode) should be public #46959

@jhudsoncedaron

Description

@jhudsoncedaron

Background and Motivation

Normally, ContentResult is created from a controller method Content(); however we got here when an ActionFilterAttribute has determined the request cannot continue. So we need to create a ContentHttpResult without calling any methods on a controller.

Previously we would throw out of OnActionExecuting but operations has been complaining about useless logspam.

Proposed API

namespace Microsoft.AspNetCore.Http.HttpResults;

/// <summary>
/// An <see cref="ContentHttpResult"/> that when executed
/// will produce a response with content.
/// </summary>
public sealed partial class ContentHttpResult : IResult, IStatusCodeHttpResult, IContentTypeHttpResult
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ContentHttpResult"/> class with the values
    /// </summary>
    /// <param name="content">The value to format in the entity body.</param>
    /// <param name="statusCode">The HTTP status code of the response.</param>
    /// <param name="contentType">The Content-Type header for the response</param>
-    internal ContentHttpResult(string? content, string? contentType, int? statusCode)
+    public ContentHttpResult(string? content, string? contentType, int? statusCode)
    {
        ResponseContent = content;
        StatusCode = statusCode;
        ContentType = contentType;
    }

## Usage Examples
```csharp
public override void OnActionExecuting(ActionExecutingContext context)
{
    if (lost session cookie)
    {
        if (context.HttpContext.Request.Method == "GET")
        {
              context.Result = new RedirectResult("/" /* login page */, false);
              return;
        } else {
             // Here's the new call
             context.Result = new ContentHttpResult("{\"error\":\"session expired in ajax call\"}", "application/json", 403);
             return;
       }
    }
}
-->

## Alternative Designs

````diff
+    public static ActionResult Create (string? content, string? contentType, int? statusCode) {/*...*/}

Risks

Less risk than not having it having to deal with weird implementations of IActionResult.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions