简体   繁体   English

在ASP.net MVC控制器中使用Url.Content

[英]Using Url.Content in a ASP.net MVC controller

I'm using Url.Content("~/something.jpg") to get an absolute path in a view without problem. 我正在使用Url.Content("~/something.jpg")在视图中获取绝对路径而没有问题。

I would like to use it in a controller but it doesn't work. 我想在控制器中使用它,但是它不起作用。 It returns "/something.jpg" instead of " http://www.mydomain.com/something.jpg ". 它返回"/something.jpg"而不是“ http://www.mydomain.com/something.jpg ”。

I tried several tricks found on google and stackoverflow without success. 我尝试了一些在google和stackoverflow上发现的技巧,但没有成功。

Why Url.Content() doesn't work in a controller ? 为什么Url.Content()在控制器中不起作用?

Any idea will be helpful. 任何想法都会有所帮助。

Thank you 谢谢

I am not sure why this is not working in controller probably because Url.Content is an mvc helper but I now how you can do what you want.If you want to get absolute path to your file you can try something like this: 我不确定为什么这在控制器中不起作用,可能是因为Url.Content是一个mvc帮助器,但是现在我可以按照自己的意愿进行操作。如果要获取文件的绝对路径,可以尝试以下操作:

var url=Path.Combine(Server.MapPath("../uploads"), "something.jpg");

In conclusion I think that what you need is Server.MapPath() 总之,我认为您需要的是Server.MapPath()

I finally found what i'm looking for by using new Uri(Request.Url, Url.Content("~/something.jpg")); 我终于找到了我通过使用new Uri(Request.Url, Url.Content("~/something.jpg"));寻找的new Uri(Request.Url, Url.Content("~/something.jpg")); . It returns : 它返回:

http://www.mydomain.com/something.jpg ; http://www.mydomain.com/something.jpg ;

Using only Url.Content() in a controller seems to be not enough. 在控制器中仅使用Url.Content()似乎还不够。 We have to use the Uri class to have the full URL. 我们必须使用Uri类具有完整的URL。

Anyway, thank you everybody for your help 无论如何,谢谢大家的帮助

You could have a config entry that holds your URL, and append that to the front... 您可能有一个配置条目来保存您的URL,并将其附加到前面...

var sUrlPublication = ConfigHelper.SiteUrl + Url.Content("~/....");

Add the URL to AppSettings ... 将URL添加到AppSettings ...

<appSettings>
  <add key="SiteURL" value="...."/>
</appSettings>

You could add a ConfigHelper class... 您可以添加ConfigHelper类...

using System.Configuration;

public static class ConfigHelper
{
  public static string SiteUrl
    {
      get { return ConfigurationManager.AppSettings["SiteURL"]; }
    }
}

EDIT : Or as mentioned by Robert 编辑 :或罗伯特提到

var sUrlPublication = Request.Url.Host  + Url.Content("~/....");

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

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