93 lines
3.1 KiB
C#
93 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
using appsrv.attributes;
|
|
using appsrv.server;
|
|
using System.Text;
|
|
|
|
namespace appsrv.resources
|
|
{
|
|
public class StaticClassResource : Resource
|
|
{
|
|
Type Type { get; }
|
|
|
|
|
|
Dictionary<string, FieldInfo> callableFields = new Dictionary<string, FieldInfo>();
|
|
|
|
public StaticClassResource(Type type,Resource container)
|
|
:base(type.Name,container)
|
|
{
|
|
Type = type;
|
|
|
|
foreach (MethodInfo methodInfo in Type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)){
|
|
WebCallable webCallable = methodInfo.GetCustomAttribute<WebCallable>();
|
|
if (webCallable != null){
|
|
new CallableMethodResource(methodInfo, this);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class CallableMethodResource : Resource
|
|
{
|
|
MethodInfo MethodInfo { get; }
|
|
WebCallable WebCallable { get; }
|
|
|
|
public CallableMethodResource(MethodInfo methodInfo,Resource container)
|
|
:base(
|
|
methodInfo.GetCustomAttribute<WebCallable>() != null ?
|
|
(methodInfo.GetCustomAttribute<WebCallable>().Name != null) ? methodInfo.GetCustomAttribute<WebCallable>().Name : methodInfo.Name
|
|
:methodInfo.Name,
|
|
container
|
|
)
|
|
{
|
|
MethodInfo = methodInfo;
|
|
WebCallable = methodInfo.GetCustomAttribute<WebCallable>();
|
|
}
|
|
|
|
private object[] ReadParameters(HttpRequest request)
|
|
{
|
|
ParameterInfo[] parameters = MethodInfo.GetParameters();
|
|
object[] p = new object[ parameters.Length ];
|
|
|
|
for (int n = 0; n < parameters.Length;n++)
|
|
{
|
|
ParameterInfo parameterInfo = parameters[n];
|
|
object pvalue = request.Query[parameterInfo.Name];
|
|
p[n] = Convert.ChangeType(pvalue, parameterInfo.ParameterType );
|
|
}
|
|
|
|
return p;
|
|
}
|
|
|
|
private void SerializeResult(HttpRequest request,object result){
|
|
switch (WebCallable.Serialization){
|
|
case Serialization.PLAIN:
|
|
SerializePlain(request, result);
|
|
break;
|
|
case Serialization.JSON:
|
|
break;
|
|
case Serialization.XML:
|
|
break;
|
|
}
|
|
}
|
|
|
|
private void SerializePlain(HttpRequest request,object result){
|
|
request.SetResponseHeader("Content-Type", "text/plain");
|
|
byte[] plain = Encoding.UTF8.GetBytes(result.ToString());
|
|
request.ResponseStream.Write(plain, 0, plain.Length);
|
|
}
|
|
|
|
public override void Hit(Stack<string> requestPath, HttpRequest request)
|
|
{
|
|
object[] p = ReadParameters(request);
|
|
object result = MethodInfo.Invoke(null, p);
|
|
SerializeResult(request, result);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|