我遇到一个问题,当上传文件大小超过100kb时,不会调用web api控制器。我搜索了一会儿,发现也许我应该在webconfig中设置maxRequestLength。但是如何在自托管中设置呢?
客户
public async Task<bool> Upload(DeviceFile file,string path)
{
var formData = new MultipartFormDataContent();
var request = new HttpRequestMessage();
var md5 = new MD5CryptoServiceProvider();
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,bufferSize:4096,useAsync:true);
fileStream.Position = 0;
var hash = md5.ComputeHash(fileStream);
fileStream.Position = 0;
formData.Add(
new StreamContent(fileStream),
file.Name,
file.Name,
new {
Info = file.Info,
}
);
request.Method = HttpMethod.Post;
request.Content = formData;
request.RequestUri = new Uri(client.BaseAddress,"api/file/");
try
{
var response = await client.SendAsync(request).ConfigureAwait(false);
await response.Content.ReadAsAsync<bool>().ConfigureAwait(false);
}
catch (Exception ex)
{
this.logger.Log(ex.ToString(), Category.Info, Priority.None);
}
return true;
}
服务器控制器
public async Task<HttpResponseMessage> Add()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartFormDataStreamProvider("D:/");
try
{
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Console.WriteLine(file.Headers.ContentDisposition.FileName);
Console.WriteLine("Server file path: " + file.LocalFileName);
}
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Console.WriteLine(string.Format("{0}: {1}", key, val));
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
答案 0 :(得分:0)
可以在自主机配置对象上设置MaxReceivedMessageSize。