将值传递给asp.net web api中的数据库

时间:2017-04-06 04:15:47

标签: c# asp.net asp.net-web-api

尝试使用asp.net webapi将图像保存到数据库。在此控制器中,我将图像保存到我的/Content/Banner/文件夹中。

[HttpPost]
        [Route("PostBanner")]
        [AllowAnonymous]
        public HttpResponseMessage PostBannerImage()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            try
            {
            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 * 1; //Size = 1 MB  

                    IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                    var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    if (!AllowedFileExtensions.Contains(extension))
                    {

                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else if (postedFile.ContentLength > MaxContentLength)
                    {

                        var message = string.Format("Please Upload a file upto 1 mb.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else
                    {
                        var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
                        postedFile.SaveAs(filePath);
                    }
                }

                var message1 = string.Format("Image Updated Successfully.");
                return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
            }

            var res = string.Format("Please Upload a image.");
            dict.Add("error", res);
            return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
        catch (Exception ex)
        {
            var res = string.Format("some Message");
            dict.Add("error", res);
            return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
    }

现在我需要发送 filePath 数据库。我知道我只需要将此文件路径传递给以下服务控制器。但我不知道如何通过它。任何人都可以帮我解决这个问题。

这是我的services.cs

 public async Task<int?> Addbanner(DisplayBannersDto dto)
        {
            try
            {
                var d = _dbContext.Banners
            .FirstOrDefault();



                d.Banner_Description = dto.Description;
                d.Banner_Location = dto.Location;


                //mark entry as modifed
                _dbContext.Entry(d).State = EntityState.Modified;
                await _dbContext.SaveChangesAsync();
                return d.Banner_Id;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

这是我的控制器

[HttpPost]
        [Route("AddBanner")]
        public async Task<IHttpActionResult> AddBanner(DisplayBannersDto dto)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            int? result = await _service.Addbanner(dto);
            return Ok();

        }

1 个答案:

答案 0 :(得分:1)

更改您的其他条件,如下所示:

else
{
    var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
                        postedFile.SaveAs(filePath);

    return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Created,
                Content = new StringContent(filePath, Encoding.UTF8, "application/json")
            };
}

现在,您在API响应的内容中有文件路径。

并使用该响应,如:

var displayBannersDto = new DisplayBannersDto();
displayBannersDto.Banner_Location = response.Content.ToString();

然后使用displayBannersDto作为dto调用您的AddBanner()API。