将值传递给 Web API 中的数据库 asp.net



我试图使用 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);
        }
    }

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

这是我的服务.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();
        }

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

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();

然后调用你的 AddBanner(( API,使用 displayBannersDto 作为 dto。

最新更新