maxkoshevoi / dateonlytimeonly.aspnet Goto Github PK
View Code? Open in Web Editor NEWAdds support for receiving and returning DateOnly/TimeOnly as ISO 8601 string to ASP.NET Core API
License: MIT License
Adds support for receiving and returning DateOnly/TimeOnly as ISO 8601 string to ASP.NET Core API
License: MIT License
Can you also create a DateOnly? type converter?
A DateOnly query parameter is being displayed as a DayOfWeek parameter in swagger.
Env:
ASP .Net 6.
Nuget Package:
DateOnlyTimeOnly.AspNet Version="1.0.1"
Swashbuckle.AspNetCore Version="6.1.4"
The Controller Code:
[HttpGet]
[Route("UserAssigned/{userId}/{calendarDate}")]
public async Task<ApiResponse<UserDayCalendarBookingsResponse>> GetBookingsAUserIsAssignedTo(string userId, DateOnly calendarDate)
Swagger param
calendarDate": {
"$ref": "#/components/schemas/DateOnly"
},
Swagger Schema
"DateOnly": {
"type": "object",
"properties": {
"year": {
"type": "integer",
"format": "int32",
"readOnly": true
},
"month": {
"type": "integer",
"format": "int32",
"readOnly": true
},
"day": {
"type": "integer",
"format": "int32",
"readOnly": true
},
"dayOfWeek": {
"$ref": "#/components/schemas/DayOfWeek"
},
"dayOfYear": {
"type": "integer",
"format": "int32",
"readOnly": true
},
"dayNumber": {
"type": "integer",
"format": "int32",
"readOnly": true
}
},
"additionalProperties": false
},
"DayOfWeek": {
"enum": [
0,
1,
2,
3,
4,
5,
6
],
"type": "integer",
"format": "int32"
}
Startup.cs Code
services.AddControllers(mvcOptions =>
{
mvcOptions.UseDateOnlyTimeOnlyStringConverters();
})
.ConfigureApiBehaviorOptions(behaviorOptions =>
{
behaviorOptions.SuppressModelStateInvalidFilter = true;
})
.AddJsonOptions(jsonOptions =>
{
jsonOptions.UseDateOnlyTimeOnlyStringConverters();
jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
jsonOptions.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
services.AddMvc(mvcOptions => {
mvcOptions.UseDateOnlyTimeOnlyStringConverters();
})
.AddJsonOptions(jsonOptions => {
jsonOptions.UseDateOnlyTimeOnlyStringConverters();
}
)
At the moment this package messes with the TypeConverter
attribute of DateOnly
and TimeOnly
:
Such approach should be avoided, because it unintentionally changes documented behavior of the runtime. For example,
var date = TypeDescriptor.GetConverter(typeof(DateOnly)).ConvertFromString("01.01.0001");
System.NotSupportedException: 'TypeConverter cannot convert from System.String.'
should be thrown
Exception is not thrown
The package should not mutate runtime (potentially breaking code, that relies on documented and therefore expected behavior). It's possible to add support of DateOnly
and TimeOnly
for AspNetCore via ModelBinders
Description
Library is using DateOnly.Parse
method, which invokes default behavior from .Net itself. There are no additional signatures available to configure the behavior.
Example
When day is not passed as part of the string, value is set to 1 as default. This is from .Net, not library.
Proposal
Behavior can be avoided using DateOnly.ParseExact
method with a format string but the library doesn't offer a signature to pass this value. More signatures needs to be added so user of this library can configure the behavior.
StringTypeConverterBase<>
does not pass along the incoming culture
to its abstract Parse
method. It should, and derived types should pass it along to the DateOnly.Parse
and TimeOnly.Parse
methods.
Because of the current behavior, properties such as RangeAttribute.ConvertValueInInvariantCulture and RangeAttribute.ParseLimitsInInvariantCulture have no effect when using ASP.NET ModelState binding/validation. The parsing happens in the "current" culture, which is the OS-level regional settings of the web server that the application is running on. It should be possible to avoid that by parsing using the invariant culture. That way, the web application can be deployed to servers all over the world and behave the same.
Please:
Under what license do you make this code available?
I'd like to use/extend it but need to know what control you'd like to have over that.
Thanks
The type 'System.DateOnly' is not a supported dictionary key using converter of type 'DateOnlyTimeOnly.AspNet.Converters.DateOnlyJsonConverter'.
[HttpGet]
[Route("date-foo")]
public async Task<Dictionary<DateOnly, Foo>> GetDatedFoos()
{
return results.ToDictionary(x=> x.date, x=> x.foo);
}
Hi, Program.cs
can be written differently with the latest C# version. Is it possible to use this package in a Program.cs
written in top-level statements?
My Program.cs
looks like below and I don't see where to insert the magic lines builder.Services .AddControllers(options => options.UseDateOnlyTimeOnlyStringConverters()).AddJsonOptions(options => options.UseDateOnlyTimeOnlyStringConverters());
, since there is no call to a AddControllers method with this syntax.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
// **********
// TODO: I want to be able to serialize DateOnly in my API endpoints requests/responses
endpoints.MapControllers(); // Map attribute-routed API controllers
// **********
endpoints.MapRazorPages();// Map razor pages
});
app.Run();
Thanks!
Hopefully not a newbie question however getting this error when attempting to generate a migration for the new DateOnly field I have added. This is dotnet core web api project, using sqlserver for the database. (or is saving DateOnly to SQLServer a different part of the puzzle I have to solve, with your DateOnlyTimeOnly nuget package handing getting it working through the Web API interface?)
Error:
$dotnet ef migrations add dateonlyfield
Build started...
Build succeeded.
System.InvalidOperationException: The property 'Tripstop.Birthdate' could not be mapped because it is of type 'DateOnly', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Added in Program.cs:
.
.
.
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services
.AddControllers(options => options.UseDateOnlyTimeOnlyStringConverters())
.AddJsonOptions(options => options.UseDateOnlyTimeOnlyStringConverters());
var app = builder.Build();
.
.
.
Then added to my model class:
public DateOnly Birthdate { get; set; }
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.