Skip to content

Commit 0685e3e

Browse files
committed
ASP003 don't use nullable type when not optional. Close #35.
1 parent 4770954 commit 0685e3e

2 files changed

Lines changed: 53 additions & 4 deletions

File tree

AspNetCoreAnalyzers.Tests/ASP003ParameterTypeTests/CodeFix.cs

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,13 @@ namespace ValidCode
4343
[ApiController]
4444
public class OrdersController : Controller
4545
{
46-
[HttpGet(""api/orders/{id:int}"")]
46+
[HttpGet(""api/orders/{id}"")]
4747
public IActionResult GetId(↓byte id)
4848
{
4949
return this.Ok(id);
5050
}
5151
}
52-
}".AssertReplace("\"api/orders/{id:int}\"", template);
52+
}".AssertReplace("\"api/orders/{id}\"", template);
5353

5454
var fixedCode = @"
5555
namespace ValidCode
@@ -59,15 +59,55 @@ namespace ValidCode
5959
[ApiController]
6060
public class OrdersController : Controller
6161
{
62-
[HttpGet(""api/orders/{id:int}"")]
62+
[HttpGet(""api/orders/{id}"")]
6363
public IActionResult GetId(byte id)
6464
{
6565
return this.Ok(id);
6666
}
6767
}
68-
}".AssertReplace("\"api/orders/{id:int}\"", template)
68+
}".AssertReplace("\"api/orders/{id}\"", template)
6969
.AssertReplace("byte id", parameter);
7070
AnalyzerAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, code, fixedCode);
7171
}
72+
73+
[TestCase("int?")]
74+
[TestCase("Nullable<int>")]
75+
public void WhenOptional(string parameter)
76+
{
77+
var code = @"
78+
namespace ValidCode
79+
{
80+
using System;
81+
using Microsoft.AspNetCore.Mvc;
82+
83+
[ApiController]
84+
public class OrdersController : Controller
85+
{
86+
[HttpGet(""api/orders/{id}"")]
87+
public IActionResult GetId(↓int? id)
88+
{
89+
return this.Ok(id);
90+
}
91+
}
92+
}".AssertReplace("int?", parameter);
93+
94+
var fixedCode = @"
95+
namespace ValidCode
96+
{
97+
using System;
98+
using Microsoft.AspNetCore.Mvc;
99+
100+
[ApiController]
101+
public class OrdersController : Controller
102+
{
103+
[HttpGet(""api/orders/{id}"")]
104+
public IActionResult GetId(int id)
105+
{
106+
return this.Ok(id);
107+
}
108+
}
109+
}";
110+
AnalyzerAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, code, fixedCode);
111+
}
72112
}
73113
}

AspNetCoreAnalyzers/Analyzers/AttributeAnalyzer.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,15 @@ private static bool HasWrongType(ParameterPair pair, out string correctType)
196196
return correctType != null;
197197
}
198198
}
199+
200+
if (!constraints.TryFirst(x => x.Span.Equals("?", StringComparison.Ordinal), out _) &&
201+
parameter.Type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T &&
202+
parameter.Type is INamedTypeSymbol namedType &&
203+
namedType.TypeArguments.TrySingle(out var typeArg))
204+
{
205+
correctType = typeArg.ToString();
206+
return true;
207+
}
199208
}
200209

201210
correctType = null;

0 commit comments

Comments
 (0)