从xamarin调用文件上载服务无法正常工作

时间:2018-05-05 10:07:34

标签: c# asp.net-mvc xamarin xamarin.forms xamarin.android

我写了一个web api来将文件上传到服务器。下面是代码。 C#WebAPI 2

public async Task<HttpResponseMessage> PostAttachments()
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    var httpRequest = HttpContext.Current.Request;

    foreach (string file in httpRequest.Files)
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

        var postedFile = httpRequest.Files[file];
        if (postedFile != null && postedFile.ContentLength > 0)
        {
            int MaxContentLength = 1024 * 1024 * 25; //Size = 5 MB

            //IList<string> AllowedMimes = new List<string> { "image/jpeg" , "image/png", "",""};
            var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.')).ToLower();
            //var extension = ext.ToLower();
            string mime = postedFile.ContentType.ToLower();
            if (!MimeTypes.ForDocuments.Contains(mime))
            {
                return Request.CreateResponse(HttpStatusCode.NotAcceptable, new ActionOutput
                {
                    Status = ActionStatus.Error,
                    Message = "Please Upload a valid document only!"
                });
            }
            else if (postedFile.ContentLength > MaxContentLength)
            {
                return Request.CreateResponse(HttpStatusCode.NotAcceptable, new ActionOutput
                {
                    Status = ActionStatus.Error,
                    Message = "Please Upload a file upto 25 mb."
                });
            }
            else
            {
                DiscussionAttachedFileServiceEntity attachment = new DiscussionAttachedFileServiceEntity();
                attachment.Id = Guid.NewGuid();
                attachment.DisplayName = postedFile.FileName;
                attachment.FileName = Guid.NewGuid().ToString() + ext;
                attachment.Mime = mime;
                attachment.Size = postedFile.ContentLength;


                MemoryStream stream = new MemoryStream();
                postedFile.InputStream.CopyTo(stream);

                Guid fileId = _discussionAttachedFileService.UploadAttachment(attachment, stream);

                return Request.CreateResponse(HttpStatusCode.Created, new ActionOutput
                {
                    Status = ActionStatus.Successfull,
                    Message = "Document has been uploaded",
                    ID = fileId
                });
            }
        }
    }
    var message = string.Format("Please Upload a document.");
    return Request.CreateResponse(HttpStatusCode.NotAcceptable, new ActionOutput
    {
        Status = ActionStatus.Error,
        Message = message
    });
}

在xamarin中,我写下了代码来调用此服务来上传文件,但它根本不起作用。

Xamarin功能

public async Task<UploadAttachmentResponseModel> UploadAttachmentFile(MemoryStream stream, string fileName)
{
    using (var content = new MultipartFormDataContent())
    {
        var fileContent = new ByteArrayContent(stream.ToArray());
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "file",
            FileName = fileName
        };
        content.Add(fileContent);

        var token = LoginService.AccessToken;
        if (token == null)
        {
            if (!await LoginService.Login())
                return null;
            token = LoginService.AccessToken;
        }

        using (var client = new HttpClient(new NativeMessageHandler()))
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var uri = new Uri($"{ApplicationSettings.Scheme}://{ApplicationSettings.ServerName}/api/v1/discussion/file/PostAttachments");

            try
            {
                var response = await client.PostAsync(uri, content);

                if(response != null && response.IsSuccessStatusCode)
                {
                    var cont = await response.Content.ReadAsStringAsync();
                    if (!string.IsNullOrWhiteSpace(cont))
                    {
                        var responseModel = JsonConvert.DeserializeObject<UploadAttachmentResponseModel>(cont);
                        if (responseModel != null)
                            return responseModel;
                        else
                            return null;
                    }
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }
        return null;
    }
}

低于错误。

System.NullReferenceException: Object reference not set to an instance of an object.     at EnrichServer.Controllers.DiscussionAttachedFileController.<PostAttachments>d__11.MoveNext() in E:\Projects\Web\Enrich\main\EnrichAppServer\Server\EnrichServer\Controllers\DiscussionAttachedFileController.cs:line 162  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()

请帮助确定问题。

0 个答案:

没有答案