在为RESTful的WCF使用了newtonsoftJson转化器之后,现在需要一个新功能,为REST WCF增加一个能上传文件的借口,如果没有自定义newtonsoftJson,这个东西只需要寥寥几笔,就直接实现了文件上传,但现在自定义了之后,就不行了,因为自定义的NewtonsoftJsonDispatchFormatter类的DeserializeRequest托管了一切,让原有的WCF文件上传功能失去了作用,于是决定自己改造这个类,关于http文件上传,w3c是有rfc1867规范的,根据这个规范,就有了如下的修改。(此修改只是实现了单文件上传,多文件上传还要再次简单修改一下)
NewtonsoftJsonDispatchFormatter->DeserializeRequest方法
public void DeserializeRequest(Message message, object[] parameters)
{
//如果是上传的content-type,则不作json处理
var headers = ((HttpRequestMessageProperty)(message.Properties[HttpRequestMessageProperty.Name])).Headers;
string contenttype = headers["Content-type"];
string contentLength = headers["Content-Length"];
if (contenttype.StartsWith("multipart/form-data"))
{
//获得附件分割边界字符串
string boundary = contenttype.Substring(contenttype.IndexOf("boundary=") + "boundary=".Length);
int len = int.Parse(contentLength);
//if(!(bool)(message.Properties["UriMatched"]))
// throw new InvalidOperationException("URL not match.");
//UriTemplateMatch utr = message.Properties["UriTemplateMatchResults"] as UriTemplateMatch;
//var d = OperationContext.Current;
//var m=utr.Template.Match(