【问题标题】:'HttpContext' does not contain a definition for 'current' [duplicate]“HttpContext”不包含“当前”的定义[重复]
【发布时间】:2019-09-10 14:01:18
【问题描述】:

我想上传图片到图片文件夹,但是会显示这个错误。前面是 Angular 7。

Asp.Net Core MVC

CustomerRepo.cs

 public bool AddCustomer(ExpressWebApi.Models.CustomerModel customer)
 { 
   SqlConnection con =new SqlConnection();
   con.ConnectionString="Data Source=.;Initial Catalog=BLAbLADB;Persist Security Info=True;User ID=sa;Password=sasasa"; 

   SqlCommand cmd = new SqlCommand();
   cmd.Connection=con;

    //file upload start-----------------------
      string imageName = null;
      var httpRequest = HttpContext.Current.Request; 
      //upload the image
      var postedFile = httpRequest.Files["cusImage"];
      //Current custome filename
      imageName = new string(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
                imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
                var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
                postedFile.SaveAs(filePath); 
  //file upload end-------------------------


  cmd.CommandText=$@"INSERT INTO Customer ([CusName], [CusPassword], [CusEmail], [CusDob], [CusImage]) VALUES ('{customer.CusName}', '{customer.CusPassword}', '{customer.CusEmail}', '{customer.CusDob}','{imageName}');";

  cmd.Connection.Open();
  cmd.ExecuteNonQuery();
  cmd.Connection.Close();

  return true;
 }

register.html - 在 Angular 应用程序中

   var customerData = { 
     "cusName": form.value.userName,
     "cusPassword": form.value.password,
     "cusEmail": form.value.email,
     "cusDob": form.value.dob,
     "cusImage" : this.fileToUpload
   };

 //for photo upload start---------------------------------
 handleFileInput(file:FileList){
 this.fileToUpload=file.item(0);

//show image preview
var reader = new FileReader();
reader.onload=(event:any)=>{
  this.imageUrl=event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
//for photo upload end---------------------------------

错误 CS0117“HttpContext”不包含“当前”的定义

【问题讨论】:

  • 在 Asp.Net Core 中 HttpContext 不再具有该静态属性。
  • 这可能是XY problem。提供minimal reproducible example 以阐明您的特定问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 什么/在哪里调用AddCustomer

标签: c# asp.net-mvc angular asp.net-web-api asp.net-core


【解决方案1】:

在 .NET Core 中,上下文是控制器类的一部分,作为 HttpContext 属性。请求以HttpContext.Request 的形式提供,您可以从那里访问表单数据。

但是,在 Core 中,文件上传的语法发生了变化,因此如果不进行一些更改,您上面的代码将无法正常工作。在您的情况下,您使用的是模型绑定,您需要设置您的请求模型来处理传入的文件。

以下来自ASP.NET Core docs上的Http Upload文档:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

您可以对模型中的单个文件或作为参数传递 [FromBody] 的单个文件使用相同的接口。

在您的情况下,您的传入模型应该具有如下属性:

public IFormFile cusImage {get; set;}

捕获入站文件。

【讨论】:

  • 这没有回答问题
猜你喜欢
  • 1970-01-01
  • 2018-08-07
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多