Byte
Byte

Reputation: 57

Asp .Net Core - Can't Cast Guid Exception

I am currently learning Asp .Net Core and OData and created a simple API for CRUD operations. But each time I try to post a body with a Guid, the ModelState returns invalid, because he throws a Invalid cast from 'System.String' to 'System.Guid'. and the model argument ist set to null.

I searched the internet the last three days, tweaked some code here and there, but since I have no idea what's happening, it was more a stab around the dark...

My Model:

public abstract class BaseModel
{
   public Guid Id { get; set; }
}

public class Article : BaseModel
{
   public string Name { get; set; }
   public string Description { get; set; }
   public string ShortDescription { get; set; }
}

My Action:

[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public override IActionResult Post([FromBody] Article model)
{
   if (!ModelState.IsValid)
   {
      return BadRequest(ModelState.Root?.Errors?[0]?.Exception?.Message);
   }

   // Some code here   

   return Ok();
}

My Startup:

public void ConfigureServices(IServiceCollection services)
{
   services.AddAutoMapper(typeof(Startup));
   services.AddControllers().AddNewtonsoftJson();
   services.AddSwaggerGen(c =>
   {
      c.SwaggerDoc("v1", new OpenApiInfo { Title = "Inventory Manager", Version = "v1"});
   });

   services.AddOdataSwaggerSupport();
   services.AddOData();
   services.AddControllers(options =>
   {
      foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
      {
         //outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
         outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
      }
      foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
      {
         //inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
         inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
      }

      options.EnableEndpointRouting = false;
      options.Conventions.Add(new GenericControllerRouteConvention());
   }).AddNewtonsoftJson(opt => opt.SerializerSettings.ContractResolver = new DefaultContractResolver());
            
   // DI
   services.AddDbContext<Repository.InventoryManagementDbContext>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   if (env.IsDevelopment())
   {
      app.UseDeveloperExceptionPage();
   }

   app.UseHttpsRedirection();

   app.UseSwagger();

   app.UseSwaggerUI(c =>
   {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "Inventory Manager");
   });

   app.UseRouting();

   app.UseEndpoints(endpoints =>
   {
      endpoints.MapControllers();
      endpoints.Select().Filter().Expand().OrderBy().Count();
      endpoints.MapODataRoute("odata", "odata", GetEdmModel(app.ApplicationServices));
   });
            
   using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
   {
      var context = serviceScope.ServiceProvider.GetService <Repository.InventoryManagementDbContext> ();
      context.Database.Migrate();
   }
}

public IEdmModel GetEdmModel(IServiceProvider serviceProvider)
{
   var builder = new ODataConventionModelBuilder(serviceProvider);
   builder.EntitySet<Article>("Articles");
   builder.EntitySet<Transaction>("Transactions");
   builder.EntitySet<Location>("Locations");
   return builder.GetEdmModel();
}

The query: The Query

Upvotes: 0

Views: 543

Answers (1)

Rena
Rena

Reputation: 36605

You need send data in Postman like below:

{
   "[email protected]": "#Guid",
   "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
   "name":"dolor nulla"
   //more data...
}

Upvotes: 2

Related Questions