MongoDb.GridFS.FindOneById returns 空
MongoDb.GridFS.FindOneById returns null
我正在使用以下代码将图片上传到服务器:
public ActionResult AttachImage(HttpPostedFileBase file)
{
var options = new MongoGridFSCreateOptions
{
Id = ObjectId.GenerateNewId().ToString(),
ContentType = file.ContentType
};
Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
return RedirectToAction("Index");
}
并尝试获取如下文件:
public ActionResult GetImage(string id)
{
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
if(image == null)
{
return HttpNotFound();
}
return File(image.OpenRead(), image.ContentType);
}
上传后我可以在数据库中看到文件,但是当我尝试将其加载为
Context.Database.GridFS.FindOneById(new ObjectId(id));
我总是得到 null。你能指出我做错了什么吗?
public class DbContext
{
public MongoDatabase Database;
public DbContext()
{
var client = new MongoClient(Properties.Settings.Default.ConnectionString);
var server = client.GetServer();
Database = server.GetDatabase(Properties.Settings.Default.DatabaseName);
}
}
mongocsharp 驱动程序 2.5.0
mongo 服务器 3.6
原来是我按Id找错文件了
而不是
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
我应该使用
var image = Context.Database.GridFS.FindOneById(id);
我使用了以前版本驱动程序示例中的代码,但在 2.5 中我们不需要使用
new ObjectId(id)
我正在使用以下代码将图片上传到服务器:
public ActionResult AttachImage(HttpPostedFileBase file)
{
var options = new MongoGridFSCreateOptions
{
Id = ObjectId.GenerateNewId().ToString(),
ContentType = file.ContentType
};
Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
return RedirectToAction("Index");
}
并尝试获取如下文件:
public ActionResult GetImage(string id)
{
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
if(image == null)
{
return HttpNotFound();
}
return File(image.OpenRead(), image.ContentType);
}
上传后我可以在数据库中看到文件,但是当我尝试将其加载为
Context.Database.GridFS.FindOneById(new ObjectId(id));
我总是得到 null。你能指出我做错了什么吗?
public class DbContext
{
public MongoDatabase Database;
public DbContext()
{
var client = new MongoClient(Properties.Settings.Default.ConnectionString);
var server = client.GetServer();
Database = server.GetDatabase(Properties.Settings.Default.DatabaseName);
}
}
mongocsharp 驱动程序 2.5.0 mongo 服务器 3.6
原来是我按Id找错文件了
而不是
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
我应该使用
var image = Context.Database.GridFS.FindOneById(id);
我使用了以前版本驱动程序示例中的代码,但在 2.5 中我们不需要使用
new ObjectId(id)