如何获得我的网站运行的相对URI

本文关键字:相对 URI 运行 网站 何获得 我的 | 更新日期: 2023-09-27 18:15:20

我有一个菜单,用户可以上传他们的头像,我想把文件路径保存在磁盘上,图像所在的位置。

[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并使用它来保存路径?还是有更好的办法?

如何获得我的网站运行的相对URI

试试这个:

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