繁体   English   中英

如何获取我的网站在哪里运行的相对URI?

[英]How to get the relative URI of where my website is running?

我有一个菜单,用户可以在其中上传他们的头像,我想将该文件路径保存在该图像所在的光盘上。

[HttpPost]
public ActionResult ChangePicture(HttpPostedFileBase file)
{
    using (EFJugadorRepository jugadorRepository = new EFJugadorRepository())
    {
        var jugador = jugadorRepository.FindJugadorByEmail(User.Identity.Name);

        if (file != null && file.ContentLength > 0)
        {

            var extension = Path.GetExtension(file.FileName);
            string fileName = String.Format("{0}{1}", User.Identity.Name, extension);

            var path = Path.Combine(Server.MapPath("~/Public/Avatars"), fileName);
            file.SaveAs(path);

            using (EFFotografiaRepository fotografiaRepository = new EFFotografiaRepository())
            {
                var fotografia = fotografiaRepository.FindAllFotografias().SingleOrDefault(f => f.fotCodigo == jugador.jugCodigo);
                if (fotografia == null)
                {
                    fotografia = new taFotografia();
                    fotografiaRepository.CreateNewFotografia(fotografia);
                }

                fotografia.fotCodigo = (int)jugador.jugCodigo;
                fotografia.fotTipo = 0;


                //string relativeRootPath = Url.Content("~/Public/Avatars");
                string relativeRootPath = "http://localhost:23188/Public/Avatars";
                fotografia.fotUrl = String.Format("{0}/{1}", relativeRootPath, fileName);
                fotografiaRepository.SaveChanges();

                jugador.jugFoto = fotografia.fotCodigo;
                jugadorRepository.SaveChanges();
            }
        }

        // redirect back to the index action to show the form once again
        return RedirectToAction("CropPicture");
    }
}

如果您注意到了,我注释了一行:

string relativeRootPath = Url.Content("~/Public/Avatars");`

可以理解,这没有用。 并且我不得不手动输入URI“ localhost”。

有没有一种方法可以获取根URI并使用它来保存路径? 或者,还有更好的方法?

尝试这个:

string path1 = HttpContext.Current.Request.ApplicationPath;
string realPath = HttpContext.Current.Request.MapPath(path1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM