Asp .Net Core - 无法转换 Guid 异常
Asp .Net Core - Can't Cast Guid Exception
我目前正在学习 Asp .Net Core 和 OData,并为 CRUD 操作创建了一个简单的 API。但是每次我尝试 post 带有 Guid 的主体时,ModelState returns 无效,因为他抛出 Invalid cast from 'System.String' to 'System.Guid'.
并且模型参数设置为 null
.
过去三天我在互联网上搜索,到处调整了一些代码,但由于我不知道发生了什么,所以更像是在黑暗中刺伤...
我的模特:
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; }
}
我的操作:
[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();
}
我的创业公司:
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();
}
查询:
您需要像下面这样在 Postman 中发送数据:
{
"id@odata.type": "#Guid",
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name":"dolor nulla"
//more data...
}
我目前正在学习 Asp .Net Core 和 OData,并为 CRUD 操作创建了一个简单的 API。但是每次我尝试 post 带有 Guid 的主体时,ModelState returns 无效,因为他抛出 Invalid cast from 'System.String' to 'System.Guid'.
并且模型参数设置为 null
.
过去三天我在互联网上搜索,到处调整了一些代码,但由于我不知道发生了什么,所以更像是在黑暗中刺伤...
我的模特:
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; }
}
我的操作:
[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();
}
我的创业公司:
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();
}
查询:
您需要像下面这样在 Postman 中发送数据:
{
"id@odata.type": "#Guid",
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name":"dolor nulla"
//more data...
}