-2

I uploading files in asp.net core mvc i create folder for images in wwwroot with the name of photo and write a program in controller in which gives error of null _IWebHostEnvironment.WebRootPath can anybody help me.

namespace eHouse.Controllers {

public class AddPropertyRentController1 : Controller
{

    Rentdb DB =new Rentdb();
    IWebHostEnvironment _IWebHostEnvironment;
    public IActionResult aprent()
    {
        return View();
    }
    [HttpPost]
    public IActionResult aprent([Bind] RentModel ar)
    {


        if (ar.imge1 != null)
        {
            string folder = "image/";
            folder += ar.imge1.FileName + Guid.NewGuid().ToString();
            ar.pic1 = folder;

            string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
            ar.imge1.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
            
        }
DavidG
  • 113,891
  • 12
  • 217
  • 223

1 Answers1

1

I have test your code, and I meet the same error as you. When I add parameter to AddPropertyRentController1 to set the value for the _IWebHostEnvironment then the error disappear.

Try to add below code:

public class AddPropertyRentController1 : Controller
{
         private IWebHostEnvironment _IWebHostEnvironment;
         public AddPropertyRentController1(IWebHostEnvironment IWebHostEnvironment)
                {
                   _IWebHostEnvironment = IWebHostEnvironment;
                }
}
  

      
Qing Guo
  • 6,041
  • 1
  • 2
  • 10
  • Simply adding code with no explanation does not make a good answer. – DavidG Oct 24 '22 at 09:47
  • Ok, I update my answer , I will notice next time. Thanks. – Qing Guo Oct 24 '22 at 10:00
  • Thanks its use full for me but now i have some issue in model.state in which validation state of pic is invalid and i put no validation kindly guide me if (ModelState.IsValid) { string res = DB.Saverecord(ar); string pics = DB.imagedb(ar); TempData["msg"] = res; } – Creative Things Oct 24 '22 at 10:38
  • @CreativeThings If my answer help you resolve your 'System.Null Reference ", could you please accept as answer? Refer to:[How to access an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) Thanks. The some issue in model.state , you can create a new post to describe the problem clearly so that we can help you. – Qing Guo Oct 25 '22 at 01:53