简体   繁体   中英

Umbraco get media from url

I want to protect my media by a genericHandler.ashx. I have a rewrite rule /media to /handlers/my-handler.ashx?media-url=xxx.jpg But I cannot find a function in umbraco api to get nodeId from url.

At the moment I use this sql query:

public static Int32 GetNodeIdFromUrl(String url)
{
        SqlParameter[] sqParams = { new SqlParameter("@url", url) };
        string sql = "select contentNodeId from cmsPropertyData where dataNvarchar =     @url";
        int id = -1;
        try
        {

           id = (int)SqlHelper.ExecuteScalar(umbraco.GlobalSettings.DbDSN,CommandType.Text,sql,sqParams);
        }
        catch (Exception ex)
        {
            umbraco.BusinessLogic.Log.Add(
                umbraco.BusinessLogic.LogTypes.Error, 
                new umbraco.BusinessLogic.User(0), 0,
                "Error from download security handler ->" + ex.Message.ToString());
        }

        return id;
    }

inspired by http://our.umbraco.org/forum/developers/api-questions/4284-getting-media-Id-from-path

do you know any umbraco api function to do this before?

i think if you know the correct format of the url, you can take the media id by using some regular expression or by splitting the url.

If you have a redirect set up to map anything from /media to /handlers/my-handler.ashx, then the original URL request will be in the format /media/{mediaID}/{fileName}.{extension}. The media ID is the name of the folder inside the /media directory on disk. When you get an incoming request, simply SubString everything after "/media/" and before the next "/".

HTH,

Benjamin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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