1

我想使用 ASP.NET MVC Web API 将图像从 Windows Phone 客户端上传到服务器,但我遇到了麻烦。

我的服务器有这个代码:

        [System.Web.Mvc.HttpPost]
    public HttpResponseMessage UploadProfileImage([FromUri]int userId)
    {
        var task = this.Request.Content.ReadAsStreamAsync();
        task.Wait();
        Stream requestStream = task.Result;

        var user = _context.Users.Where(x => x.UserId == userId).FirstOrDefault();

        var res = System.IO.Path.GetDirectoryName(user.ProfileImagePath);
        res = System.IO.Path.Combine(res, string.Format("ProfileImage{0}.jpg", user.UserName));
        string filePath = System.Web.Hosting.HostingEnvironment.MapPath(res);

        try
        {
            FileStream fs = System.IO.File.OpenWrite(filePath);
            requestStream.CopyTo(fs);
            fs.Close();

            user.ProfileImagePath = res;
            _context.Entry(user).State = EntityState.Modified;
            _context.SaveChanges();
        }
        catch (Exception)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }

        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.Created;
        return response;
    }

在 WP 客户端中,我尝试使用这种方法上传图像:

        public void UpdateProfileImage(byte[] image)
    {                                           
        string serviceUri = string.Format("http://localhost:4879/api/Application/UploadProfileImage?userId={0}", StaticDataManager.CurrentUserId);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUri);
        request.Headers["userId"] = StaticDataManager.CurrentUserId.ToString();
        request.Method = "POST";
        string message = "";
        request.BeginGetRequestStream(result =>
        {
            Stream requestStream = request.EndGetRequestStream(result);
            requestStream.Write(image, 0, image.Length);
            request.BeginGetResponse(result2 =>
            {
                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result2);
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        message = "Its working";
                    }
                    else
                    {
                        message = "Something goes wrong";
                    }
                }
                catch(Exception ex)
                {
                    message = ex.Message;
                }
            }, null);
        }, null);
    }

但是当我尝试上传图片时,我得到了这个异常: 例外

4

0 回答 0