I get a Date in an ASP.NET Core Controller like this:
public class MyController:Controller{
public IActionResult Test(DateTime date) {
}
}
Try setting the culture manually in your web.config
<configuration>
<system.web>
<globalization culture="de-DE" uiCulture="de-DE"/>
</system.web>
</configuration>
EDIT: Since i just realized this is Core, you can do it this way in StartUp.Configure:
var cultureInfo = new CultureInfo("de-DE");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
If you don't mind using the generic StatusCode method to make this call, you can do something like the following:
internal IActionResult CreateResponse(int code, object content = null)
{
Type t = content?.GetType();
bool textContent = t == typeof(string) || t == typeof(bool);
//
JsonSerializerSettings dateFormatSettings = new JsonSerializerSettings
{
DateFormatString = myDateFormat
};
string bodyContent = content == null || string.IsNullOrWhiteSpace(content + "")
? null
: textContent
? content + ""
: JsonConvert.SerializeObject(content, dateFormatSettings);
ObjectResult or = base.StatusCode(code, bodyContent);
string mediaType =
!textContent
? "application/json"
: "text/plain";
or.ContentTypes.Add(new MediaTypeHeaderValue(mediaType));
return or;
}
You can add this to a base class and call it like:
return base.CreateResponse(StatusCodes.Status200OK, new { name = "My Name", age = 23});
It's up to you if you want to create your own Ok, BadRequest, etc...methods, but for me this works and I hope it helps anybody else. You could even default int code = 200, if most of your requests are GETs. This code assumes you either want to respond with a string, boolean, or a custom object, but you can easily handle all primitives by checking Type.GetTypeInfo().IsPrimitive and even doing some checks for decimal, string, DateTime, TimeSpan, DateTimeOffset, or Guid.
I had same problem ad almost got mad. I tried everthing with no sucsses. First I found a workaround to solve part of my problem:
Workaround:
string data1
string horainicio
string horafim
var ageData = new AgendaData();
var user = await _userManager.GetUserAsync(User);
string usuario = user.Id;
int empresa = user.IdEmpresa;
int Idprospect = Convert.ToInt32(prospect);
int minutos = 0;
var tipoAgenda = TipoAgenda.Contato;
var provider = CultureInfo.InvariantCulture;
provider = new CultureInfo("en-US");
string formato = "dd/MM/yyyy HH:mm";
var dataInicio = DateTime.ParseExact(data1 + " " + horainicio, formato, provider);
var dataFim = DateTime.ParseExact(data1 + " " + horafim, formato, provider);
var dataAlerta = dataInicio.AddMinutes(-minutos);
But, this way i aways have to set invariantculture to all my datetime. I found the solution setting my culture at the configure on startup.cs.
Set Culture on startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CRMContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
//Fixar Cultura para en-US
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions
{
SupportedCultures = new List<CultureInfo> { new CultureInfo("en-US") },
SupportedUICultures = new List<CultureInfo> { new CultureInfo("en-US") },
DefaultRequestCulture = new RequestCulture("en-US")
};
app.UseRequestLocalization(localizationOptions);
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
context.Database.EnsureCreated();
}
Hope this help you.
I wanted to format the dates in my responses and I did the following in ConfigureServices method:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.DateFormatString = "mm/dd/yy, ffffdd";
});
Hope that helps.