0

用户界面

<input type = "file" title="Please upload some file" name="file" />

MVC

/*below method is called from a MVC controller 
 this method resides for now in MVC project itself*/
public IEnumerable<CustomerTO> FetchJson(HttpPostedFile file)
    {
        using (StreamReader sr = new StreamReader(file.FileName))
        {
            {
                file.saveAs("details.txt");
                string json = sr.ReadToEnd();
                IEnumerable<CustomerTO> customers=
                    JsonConvert.DeserializeObject<List<CustomerTO>>(json);
               return customers; 
            }
        }
    }

当 MVC 项目或某种基于 Web 的项目中的上述方法时,所有引用都很好。

但我正在考虑创建一个实用程序类来处理所有此类操作。所以我创建了一个类库项目并添加了一个类 Utitlity.cs

类库

public IEnumerable<CustomerTO> FetchJson(HttpPostedFile file)
    {
        //but HttpPostedFile is throwing error.
        //NOTE Ideally,I shouldn't be saving the posted file
    }

现在我知道 FileUpload 是 UI 控件 HttpPostedFile 处理与此相关的所有操作。

我可以轻松添加参考using System.Web,但我怀疑这是否正确?

但是我如何在没有任何开销的情况下满足我的要求呢? 内存分配、执行和所有这些都非常关键

4

1 回答 1

1

一旦确保控制器方法正确接收发布的文件引用,请阅读此答案。

您不需要System.Web在类库中添加引用。相反,只需将文件内容传递给重构的方法。此外,由于您正在创建实用程序类,请确保它可以返回任何类型的 DTO 而不仅仅是CustomerDTO. 例如,如果您需要传入 Accounts 文件并从中AccountDTO取出,您应该能够使用相同的类/方法。

事实上,您应该能够使用该代码将任何字符串内容反序列化为您想要的任何类型。你可以Generics在这里使用。

// Controller.cs
public IEnumerable<CustomerTO> FetchJson(HttpPostedFile file) 
{
    string fileContent;
    using (StreamReader sr = new StreamReader(file.FileName)) {
        file.saveAs("details.txt");
        fileContent = sr.ReadToEnd();
    }

    var customers = JsonSerializer.Deserialize<List<CustomerTO>>(content); // Refactored

    return customers; 
}

// JsonSerializer.cs
public static T Deserialize<T>(string content) {
    // ...
    return JsonConvert.DeserializeObject<T>(content);
}

在 Controller 中读取文件内容StreamReader不需要重构。那是不必要的IMO。

于 2017-07-29T07:19:51.223 回答