Home > Net >  The.net core reflection MVC parameters
The.net core reflection MVC parameters

Time:12-16

Here have a controller, call Api, the controller has a Action Rest receive all Post method, and all requests must be brought into a parameter method, known as the routing orientation controller directly, the parameters of the controller automatically map, but when Rest upon receipt of the request, according to the method name, access to private methods in ActionName=method method, then need to reflect the parameters in the frombody into private method parameter object, how to do?
 
Private MethodInfo GetMethodInfo (string methodName)
{
If (string. IsNullOrEmpty (methodName)) return null;

MethodInfo method;
The Methods. TryGetValue (methodName, out method);

The return method;
}

[HttpPost]
Public async Task Rest (string method)
{
Try
{
Var methodfunc=GetMethodInfo (method);
If (methodfunc==null)
{
Return Ok (new ApiReponse () {Code="0001", Msg=$" method: "+ method +" does not exist!" });
}

StreamReader bodyreader=new StreamReader (Request. Body);
Var bodystr=await bodyreader. ReadToEndAsync ();

Var result=await (methodfunc. Invoke (this, new object [] {}) as TaskIf (result==null)
{
Return BadRequest (new ApiReponse () {Code="0001", Msg=$" method: "+ method +" no normal return result!" });
}



return result;
}
The catch (Exception ex)
{
Return BadRequest (new ApiReponse () {Code="0001", Msg=$" abnormal call interface: method: "+" exception information: "+ ex + method. The ToString ()});
}
}

[ActionName (" items. The synchronize ")]
Private async Task ItemsSynchronize ([FromBody] ItemsSynchronizeRequest request)
{
Try
{
Return Ok (new ApiReponse ()
{
Code="9998",
An unknown error Msg=", "
});
}
The catch (Exception ex)
{
Return BadRequest (new ApiReponse ()
{
Code="9998",
Msg="unknown error:" + ex. Message
});
}
}

CodePudding user response:

Unless you have to use less reflection, if you have any requirements on the performance comparison, the one hundred times tend to see the performance difference,
  • Related