zijianhuang / webapiclientgen

Strongly Typed Client API Generators generate strongly typed client APIs in C# .NET and in TypeScript for jQuery and Angular 2+ from ASP.NET Web API and .NET Core Web API
MIT License
167 stars 38 forks source link

Utilize NotNullAttribute and MayBeNull for HelpStrictMode #121

Open zijianhuang opened 2 years ago

zijianhuang commented 2 years ago

Currently HelpStrictMode may almost always give a return type an optional null type. However, some APIs always give a proper object / value back. It will be nice that the codegen utilizes NotNullAttribute , and not to give optional null type upon such decoration.

NotNullAttribute https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.notnullattribute?view=net-6.0 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis

zijianhuang commented 2 years ago

https://www.meziantou.net/csharp-8-nullable-reference-types.htm very good article.

I am thinking of copying some CodeAnslysis attributes to client codes, but I am not sure if such attributes are available during runtime. Anyway, I can build some local test cases to find out. And https://stackoverflow.com/questions/71144165/notnullattribute-missing-when-checking-by-reflection may apply to .net notnullattribute. https://stackoverflow.com/questions/58453972/how-to-use-net-reflection-to-check-for-nullable-reference-type https://codeblog.jonskeet.uk/2019/02/10/nullableattribute-and-c-8/

However, regarding to class properties, probably RequiredAttribute and DataContract[IsRequired] could be good enough.

zijianhuang commented 2 years ago

Option: Support NotNullAttributeOnMethod, SupportNullReferenceOnMethodReturn

If NotNull decorates return

  1. CS Codes will have NotNull copied over.
  2. TS codes will not have null as optional type for return, when HelpStrictMode is true.

When server CS codes return parameter has nullable reference types turned on, System.Runtime.CompilerServices.NullableContextAttribute exists with value 1 or 2 (with question mark).

  1. In CS codes, copy the question marks over.
  2. in TS codes, copy the question mark over, or use null?
zijianhuang commented 2 years ago

Both NotNullAttribute and nullable reference types are the concerns of the service programming, checked during compiling or CA. Not all such concerns apply to the client side programming. For example, it is not feasible to copy the constructors dealing with nullable reference types to the client codes. Also, typescripts codes have interfaces for models, not classes, even though other codegen may support client classes.

Currently, in TypeScript client codes, all model properties are optional decorated with a question mark, unless the property is decorated with RequiredAttribute or MemberData(IsRequired=true).