Do not throw when a status code with a codefix appears multiple times in the method body

Fixes https://github.com/aspnet/AspNetCore/issues/4480
This commit is contained in:
Pranav K 2018-12-31 15:46:01 -08:00
parent b1f4a7bafd
commit d52672748a
4 changed files with 81 additions and 1 deletions

View File

@ -169,7 +169,12 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
}
var statusCode = metadata.IsDefaultResponse ? 200 : metadata.StatusCode;
statusCodes.Add(statusCode, (statusCode, metadata.ReturnType));
if (!statusCodes.ContainsKey(statusCode))
{
// If a status code appears multiple times in the actual metadata, pick the first one to
// appear in the codefix
statusCodes.Add(statusCode, (statusCode, metadata.ReturnType));
}
}
return statusCodes.Values;

View File

@ -51,6 +51,9 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
[Fact]
public Task CodeFixAddsStatusCodesFromObjectInitializer() => RunTest();
[Fact]
public Task CodeFixWorksWhenMultipleIdenticalStatusCodesAreInError() => RunTest();
private async Task RunTest([CallerMemberName] string testMethod = "")
{
// Arrange

View File

@ -0,0 +1,34 @@
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.AspNetCore.Mvc.Api.Analyzers._INPUT_
{
[ApiController]
[Route("[controller]/[action]")]
public class CodeFixWorksWhenMultipleIdenticalStatusCodesAreInError : ControllerBase
{
public List<CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel> Values { get; } =
new List<CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel>();
public ActionResult<CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel> GetItem(int id)
{
if (id == 0)
{
return NotFound();
}
var model = Values.FirstOrDefault(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return model;
}
}
public class CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel
{
public int Id { get; set; }
}
}

View File

@ -0,0 +1,38 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc.Api.Analyzers._OUTPUT_
{
[ApiController]
[Route("[controller]/[action]")]
public class CodeFixWorksWhenMultipleIdenticalStatusCodesAreInError : ControllerBase
{
public List<CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel> Values { get; } =
new List<CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel>();
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesDefaultResponseType]
public ActionResult<CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel> GetItem(int id)
{
if (id == 0)
{
return NotFound();
}
var model = Values.FirstOrDefault(m => m.Id == id);
if (model == null)
{
return NotFound();
}
return model;
}
}
public class CodeFixWorksWhenMultipleIdenticalStatusCodesAreInErrorModel
{
public int Id { get; set; }
}
}