這邊有個控制器,叫Api,控制器有個Action Rest接收所有Post方法,而所有請求中必須帶入一個引數method,已知當路由直接定向控制器的時候,控制器的引數自動映射,但是當Rest收到請求時,根據method名稱,獲取私有方法中ActionName=method的方法,這時候需要將frombody里的引數反射成私有方法的引數物件,一般怎么做好?
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
});
}
}
uj5u.com熱心網友回復:
除非必須,否則少用反射。如果對性能比較有要求,這往往會看到上百倍的性能差別。轉載請註明出處,本文鏈接:https://www.uj5u.com/net/235291.html
標籤:ASP.NET
