Last active
March 5, 2019 07:44
-
-
Save seangwright/29e26418cf047e0e783107213757a2ad to your computer and use it in GitHub Desktop.
ken120-mvc-vuejs-MediaLibraryApi.ashx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Web; | |
using CMS.Helpers; | |
using CMS.MediaLibrary; | |
using CMS.Membership; | |
using CMS.SiteProvider; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
namespace CMSApp.CMSPages | |
{ | |
/// <summary> | |
/// Endpoint for Mvc widgets needing to query the media library | |
/// </summary> | |
public class MediaLibraryApi : IHttpHandler | |
{ | |
private static readonly JsonSerializerSettings serializerSettings = | |
new JsonSerializerSettings | |
{ | |
ContractResolver = new CamelCasePropertyNamesContractResolver(), | |
Formatting = Formatting.Indented | |
}; | |
public void ProcessRequest(HttpContext context) | |
{ | |
if (!AuthenticationHelper.IsAuthenticated()) | |
{ | |
return; | |
} | |
var queryString = context.Request.QueryString; | |
int pageSize = ValidationHelper.GetInteger(queryString["pageSize"], 10); | |
int pageNumber = ValidationHelper.GetInteger(queryString["pageNumber"], 0); | |
string fileName = queryString["fileName"] ?? ""; | |
string fileTitle = queryString["fileTitle"] ?? ""; | |
var query = MediaFileInfoProvider.GetMediaFiles() | |
.WhereNotNull(nameof(MediaFileInfo.FileName)) | |
.WhereNotNull(nameof(MediaFileInfo.FileSiteID)) | |
.WhereEquals(nameof(MediaFileInfo.FileSiteID), SiteContext.CurrentSiteID) | |
.Page(pageNumber, pageSize); | |
if (!string.IsNullOrWhiteSpace(fileName)) | |
{ | |
query = query.WhereContains(nameof(MediaFileInfo.FileName), fileName); | |
} | |
if (!string.IsNullOrWhiteSpace(fileTitle)) | |
{ | |
query = query.WhereContains(nameof(MediaFileInfo.FileTitle), fileTitle); | |
} | |
var files = query | |
.TypedResult | |
.Select(f => new | |
{ | |
f.FileID, | |
f.FileGUID, | |
f.FileName, | |
f.FileTitle, | |
f.FilePath, | |
f.FileSize, | |
f.FileImageWidth, | |
f.FileImageHeight, | |
f.FileModifiedWhen, | |
f.FileDescription, | |
f.FileExtension, | |
f.FileCreatedWhen, | |
PermanentUrl = MediaLibraryHelper.GetPermanentUrl(f).TrimStart('~') | |
}); | |
string responseJson = JsonConvert.SerializeObject(files, serializerSettings); | |
context.Response.ContentType = "application/json"; | |
context.Response.Write(responseJson); | |
} | |
public bool IsReusable => false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment