realist
realist

Reputation: 2375

Posting Date to Asp.net core API

I'm using asp.net core web API 2.1. I'm sending request with postman. I'm sending "10.12.2019". But, I'm getting "12.10.2019" from my controller.cs. How can I fix this error?

MyController.cs

[HttpPost]
public void MyMethod([FromBody]MyClass myClass)
{
}

public class MyClass {
    public DateTime myDate { get; set; }
}

my request

http://localhost:5012/api/MyController/MyMethod

my json

{
  "myDate": "10.12.2019"
}

My startup.cs

  services.Configure<RequestLocalizationOptions>(options =>
       {
           options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("tr-TR");
           options.SupportedCultures = new List<CultureInfo> { new CultureInfo("tr-TR") };
       });

Upvotes: 1

Views: 12231

Answers (2)

haldo
haldo

Reputation: 16701

If you want to change the culture your service uses then you can set it in Startup.cs and add it inside the Configure() method.

This works for me (add it before app.UseMVC()):

var defaultCulture = new CultureInfo("tr-TR");
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture(defaultCulture),
    SupportedCultures = new List<CultureInfo> { defaultCulture },
    SupportedUICultures = new List<CultureInfo> { defaultCulture }
});

The above will displays a date correctly in dd.MM.yyyy format when calling .ToShortDateString(). However, when POSTing a date it wouldn't bind/parse correctly.

To correctly parse a date format when POSTing you need to set the culture of the JSON serializer. We can set the culture of the JSON serializer in AddJsonOptions().

Add this to the ConfigureServices method and it should solve the issue.

services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.Culture = new CultureInfo("tr-TR"); 
        });

Upvotes: 3

Farshan
Farshan

Reputation: 436

Try this JsonConvert attribute for custom date

public class MyDateTimeConverter : IsoDateTimeConverter
{
    public MyDateTimeConverter()
    {
        base.DateTimeFormat = "dd-MM-yyyy";
    }
}

And use the attribute for your property as

public class MyClass
{
    [JsonConverter(typeof(MyDateTimeConverter))]
    public DateTime MyDate { get; set; }
}

this will automatically convert the body to the expected format.

if you are expecting all datetime properties in this format then add this global settings in your startup.cs

services.AddMvc()  
   .AddJsonOptions(options =>  
   {  
     options.SerializerSettings.DateFormatString= "dd-MM-yyyy";  
   });  

But you have to make sure all the values given for that property should be in the provided format. Hope this helps :)

Upvotes: 4

Related Questions