Type 'System.Web.HttpRequest' cannot be se

2019-09-20 07:28发布

问题:

I am trying to design an Picture Upload feature into a web site. I am using ASP.NET 3.5, C#, and WCF.

I have been asked to accomplish the following:

1) Make the Uploader a Web Service
2) Return progress updates to the user as files are uploaded.
3) Log other relevant user-selected options in the database.

So, I have started off by creating a WCF web client with the below service contract:

IService.UploadPictures(HttpRequest request);

private UploadServiceClient upload;

protected void Page_Load(object sender, EventArgs e)
{

      upload = new UploadServiceClient();
      upload.UploadPictures(Request.Files);

}

When I compile, I get the below error:

Type 'System.Web.HttpRequest' cannot be serialized. Consider marking it with the DataContractAttribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.

So, I went back into my service contract and changed [OperationContract] to [DataContract] but the change produced the same error.

Can somebody kindly tell me what I am doing wrong and provide examples as to how to best move forward?

Thanks for your time.

回答1:

You cannot use something like a HttpRequest as a WCF parameter. The error messages says it all - the HttpRequest is not serializable, and in order to work with WCF, types have to be serializable.

Also, you need to remember: you're not just passing an object instance to a method here - what you're really doing is having the WCF runtime serialize your request (the method name to call plus all the parameters passed in) into a message (think: e-mail or xml file), sending it to the server, deserialising there and building up a new copy of the given datatype (as defined in your DataContract), and doing something with it.

Your WCF service could well be self-hosted, e.g. running in a NT Service or console app - no HttpRequest available in those circumstances!

You need to definitely rearchitect your solution - you need to either check into WCF streaming to upload files to WCF (google for it - you'll find plenty of hits) or you'll need to find another way to pass the relevant info (e.g. list of filenames) to the WCF service without use of a HttpRequest object.

Marc



回答2:

You are submitting a request as a parameter to a request. This is not what you want to do. I'm assuming that "Request.Files" is an array of files. This is what you want to upload. So something like:

IService.UploadPictures(List<SomeFileType> request);