62,243
社区成员




private MethodInfo GetMethodInfo(string methodName)
{
if (string.IsNullOrEmpty(methodName)) return null;
MethodInfo method;
Methods.TryGetValue(methodName, out method);
return method;
}
[HttpPost]
public async Task<IActionResult> Rest(string method)
{
try
{
var methodfunc = GetMethodInfo(method);
if (methodfunc == null)
{
return Ok(new ApiReponse() { Code = "0001", Msg = $"method:" + method + " 不存在!" });
}
StreamReader bodyreader = new StreamReader(Request.Body);
var bodystr = await bodyreader.ReadToEndAsync();
var result = await (methodfunc.Invoke(this, new object[] {}) as Task<IActionResult>);
if (result == null)
{
return BadRequest(new ApiReponse() { Code = "0001", Msg = $"method:" + method + " 没有正常返回结果!" });
}
return result;
}
catch (Exception ex)
{
return BadRequest(new ApiReponse() { Code = "0001", Msg = $"调用接口异常:method:" + method + " 异常信息:" + ex.ToString() });
}
}
[ActionName("items.synchronize")]
private async Task<IActionResult> ItemsSynchronize([FromBody]ItemsSynchronizeRequest request)
{
try
{
return Ok(new ApiReponse()
{
Code = "9998",
Msg = "未知错误:"
});
}
catch (Exception ex)
{
return BadRequest(new ApiReponse()
{
Code = "9998",
Msg = "未知错误:" + ex.Message
});
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<TranslationTransformer>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDynamicControllerRoute<TranslationTransformer>("/Rest");
});
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
// app.UseAuthorization();
}
public class TranslationTransformer : DynamicRouteValueTransformer
{
public TranslationTransformer()
{
}
public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
var method = httpContext.Request.Query["method"];
if (values == null)
values = new RouteValueDictionary();
string[] temp = method.First().Split('.');
values["controller"]= temp[0];
values["Action"] = temp[1];
return values;
}
}
我们自己做个动态路由就好,你内部还是该怎么开发就怎么开发,外面用一个动态路由统一映射就好。下班15分钟了,我懒得折腾了,你看得懂自己完善。
using System.Reflection;
Type t = this.GetType();
var m = t.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); // 找私有方法methodName
if(m != null)
{
// 找到了
}
else
{
// 没找到
}