Skip to content

Commit

Permalink
Handle missing Accept header when _format is provided (#381)
Browse files Browse the repository at this point in the history
  • Loading branch information
cunninghamjc authored Mar 8, 2019
1 parent e8faf39 commit af6c7d7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,33 @@ public async Task GivenARequestWithAValidFormatQuerystring_WhenValidatingTheCont
await filter.OnActionExecutionAsync(context, actionExecutedDelegate);
}

[Fact]
public async Task GivenARequestWithAValidFormatQueryStringAndNoAcceptHeader_WhenValidatingTheContentType_ThenNoExceptionShouldBeThrown()
{
var filter = CreateFilter();

var context = CreateContext(Guid.NewGuid().ToString());
var actionExecutedDelegate = CreateActionExecutedDelegate(context);

context.HttpContext.Request.QueryString = new QueryString($"?_format=json");

await filter.OnActionExecutionAsync(context, actionExecutedDelegate);
}

[Fact]
public async Task GivenARequestWithAValidFormatQueryStringAndEmptyAcceptHeader_WhenValidatingTheContentType_ThenNoExceptionShouldBeThrown()
{
var filter = CreateFilter();

var context = CreateContext(Guid.NewGuid().ToString());
var actionExecutedDelegate = CreateActionExecutedDelegate(context);

context.HttpContext.Request.QueryString = new QueryString($"?_format=json");
context.HttpContext.Request.Headers.Add("Accept", string.Empty);

await filter.OnActionExecutionAsync(context, actionExecutedDelegate);
}

[Theory]
[InlineData("application/blah")]
[InlineData("application/xml")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public async Task CheckRequestedContentTypeAsync(HttpContext httpContext)
throw new UnsupportedMediaTypeException(Resources.UnsupportedFormatParameter);
}

string closestClientMediaType = _outputFormatters.GetClosestClientMediaType(resourceFormat, acceptHeaders.Select(x => x.MediaType.Value));
string closestClientMediaType = _outputFormatters.GetClosestClientMediaType(resourceFormat, acceptHeaders?.Select(x => x.MediaType.Value));

// Overrides output format type
httpContext.Response.ContentType = closestClientMediaType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal static string GetClosestClientMediaType(this IEnumerable<TextOutputForm
string closestClientMediaType = null;
string preferred = resourceFormat.ToContentType();

if (outputFormatters != null)
if (outputFormatters != null && acceptHeaders != null)
{
// Gets formatters that can write the desired format
var validFormatters = outputFormatters
Expand Down

0 comments on commit af6c7d7

Please sign in to comment.