CefSharp Custom SchemeHandler
Я использую SchemeHandler от CefSharp, чтобы получить ресурсы из моего проекта на C #, например.css
, .js
или же.png
файлы, использующие пользовательский URL, например,custom://cefsharp/assets/css/style.css
У меня есть 2 пользовательских класса для архивирования.
Первый класс,MyCustomSchemeHandlerFactory
будет тот, который обрабатывает пользовательскую схему, и это выглядит так, где «custom» будет пользовательской схемой:
internal class MyCustomSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "custom";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new MyCustomSchemeHandler();
}
}
Следующий класс, который я реализовал,MyCustomSchemeHandler
который будет принимать вызов и выводить ответ, и это выглядит так:
internal class MyCustomSchemeHandler : IResourceHandler
{
private static readonly IDictionary<string, string> ResourceDictionary;
private string mimeType;
private MemoryStream stream;
static MyCustomSchemeHandler()
{
ResourceDictionary = new Dictionary<string, string>
{
{ "/home.html", Properties.Resources.index},
{ "/assets/css/style.css", Properties.Resources.style}
};
}
public Stream Stream { get; set; }
public int StatusCode { get; set; }
public string StatusText { get; set; }
public string MimeType { get; set; }
public NameValueCollection Headers { get; private set; }
public Stream GetResponse(IResponse response, out long responseLength, out string redirectUrl)
{
redirectUrl = null;
responseLength = -1;
response.MimeType = MimeType;
response.StatusCode = StatusCode;
response.StatusText = StatusText;
response.ResponseHeaders = Headers;
var memoryStream = Stream as MemoryStream;
if (memoryStream != null)
{
responseLength = memoryStream.Length;
}
return Stream;
}
public bool ProcessRequestAsync(IRequest request, ICallback callback)
{
// The 'host' portion is entirely ignored by this scheme handler.
var uri = new Uri(request.Url);
var fileName = uri.AbsolutePath;
string resource;
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
var resourceHandler = ResourceHandler.FromString(resource);
stream = (MemoryStream)resourceHandler.Stream;
var fileExtension = Path.GetExtension(fileName);
mimeType = ResourceHandler.GetMimeType(fileExtension);
callback.Continue();
return true;
}
else
{
callback.Dispose();
}
return false;
}
void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl)
{
responseLength = stream == null ? 0 : stream.Length;
redirectUrl = null;
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusText = "OK";
response.MimeType = mimeType;
}
bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
{
//Dispose the callback as it's an unmanaged resource, we don't need it in this case
callback.Dispose();
if (stream == null)
{
bytesRead = 0;
return false;
}
//Data out represents an underlying buffer (typically 32kb in size).
var buffer = new byte[dataOut.Length];
bytesRead = stream.Read(buffer, 0, buffer.Length);
dataOut.Write(buffer, 0, buffer.Length);
return bytesRead > 0;
}
bool CanGetCookie(Cookie cookie)
{
return true;
}
bool CanSetCookie(Cookie cookie)
{
return true;
}
void Cancel()
{
}
}
Внутри этого класса я определил пользовательский словарь ресурсов, который будет определять, какой файл из ресурсов будет использоваться, как я уже говорил в первом примере:custom://cefsharp/assets/css/style.css
должен загрузить ресурсProperties.Resources.style
проблема в том, что ничего не загружается, когда я захожу на конкретный URL, я пытался вывести mimeType, и он работает, но каким-то образом сам файл не будет выводиться правильно Что-то не так с моей реализацией?
Кроме того, я попытался вывести необработанный файл в виде:
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
MessageBox.Show(resource);
}
И он выводит правильный файл без проблем.
Для загрузки пользовательской схемы я использую следующий код перед инициализацией CefSharp:
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = MyCustomSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new MyCustomSchemeHandlerFactory()
});
Вышеуказанные классы были основаны на следующих ссылках: MyCustomSchemeHandlerFactory:FlashResourceHandlerFactory.cs MyCustomSchemeHandler:CefSharpSchemeHandler.cs а такжеResourceHandler.cs