我正在尝试将一些C# MVC遗留代码移动到一个共享的DLL中。到目前为止,一切都进行得很顺利,但我被要求该共享DLL不需要以任何方式引用System.Web。
来自System.Web的DLL中唯一使用的类型是HttpPostedFileBase。
public string ChangeAttachment(int userId, HttpPostedFileBase file)
{
string attachmentsFolderPath = ConfigurationManager.AppSettings["AttachmentsDirectory"];
if (!Directory.Exists(attachmentsFolderPath))
{
Directory.CreateDirectory(attachmentsFolderPath);
}
string fileTarget = Path.Combine(attachmentsFolderPath, userId.ToString() + Path.GetExtension(file.FileName));
if (File.Exists(fileTarget))
{
File.Delete(fileTarget);
}
file.SaveAs(fileTarget);
return fileTarget;
}如您所见,这里不需要HTTP或Web功能,因为只使用它的FileName和SaveAs()成员。
是否有一种替代方法,我可以轻松地将HttpPostedFileBase转换为(调用方),这样,作为参数传递的所有内容都是一个非web文件吗?
注意:HttpPostedFileBase直接从System.Object继承,而不是从任何文件类继承。
发布于 2016-03-27 17:17:47
HttpPostedFileBase是一个抽象类。因此,挑战在于,您实际上不是要替换该类,而是要替换HttpPostedFileWrapper,后者是实现。(这不是类继承的内容,而是类继承的内容。)
HttpPostedFileWrapper反过来引用其他System.Web类,如HttpInputStream和'HttpPostedFile`‘。
所以你不能换掉它。也许,通过要求您不要引用System.Web,目的是要移动与web功能无关的遗留代码,比如业务逻辑。如果不能将代码完全排除在外,也许可以将其排除在正在创建的新程序集中之外,然后再创建另一个引用System.Web的程序集。如果他们不需要这个特定的功能,他们只引用一个程序集,但是如果他们需要这个,那么他们也可以添加第二个程序集,它引用System.Web。
发布于 2016-03-27 20:39:39
如果您不想引用System.Web并且也想使用救济金方法,您可以定义一个接口,也可以定义一个包装器来创建一个链接。然而,这并不是一个非常简单的方法:
//// Second assembly (Without referencing System.Web):
// An interface to link the assemblies without referencing to System.Web
public interface IAttachmentFile {
void SaveAs(string FileName);
}
..
..
// Define ChangeAttachment method
public string ChangeAttachment(int userId, IAttachmentFile attachmentFile) {
string attachmentsFolderPath = ConfigurationManager.AppSettings["AttachmentsDirectory"];
if (!Directory.Exists(attachmentsFolderPath)) {
Directory.CreateDirectory(attachmentsFolderPath);
}
string fileTarget = Path.Combine(
attachmentsFolderPath,
userId.ToString() + Path.GetExtension(file.FileName)
);
if (File.Exists(fileTarget)) {
File.Delete(fileTarget);
}
// This call leads to calling HttpPostedFileBase.SaveAs
attachmentFile.SaveAs(fileTarget);
return fileTarget;
}
//// First assembly (Referencing System.Web):
// A wrapper class around HttpPostedFileBase to implement IAttachmentFile
class AttachmentFile : IAttachmentFile {
private readonly HttpPostedFileBase httpPostedFile;
public AttachmentFile(HttpPostedFileBase httpPostedFile) {
if (httpPostedFile == null) {
throw new ArgumentNullException("httpPostedFile");
}
this.httpPostedFile = httpPostedFile;
}
// Implement IAttachmentFile interface
public SaveAs(string fileName) {
this.httpPostedFile.SaveAs(fileName);
}
}
..
..
// Create a wrapper around the HttpPostedFileBase object
var attachmentFile = new AttachmentFile(httpPostedFile);
// Call the ChangeAttachment method
userManagerObject.ChangeAttachment(userId, attachmentFile);https://stackoverflow.com/questions/36249169
复制相似问题