从其他C#服务器端控制器调用ASP.NET post route

时间:2022-05-08 15:23:46

This is for a web application that has a C# back-end. The way it is architected I am not able to just import one of these classes to the other to call the method directly. Unfortunately, we have something going wrong with our build process, so I am unable to debug this code, so I'm hoping to nail it in as few iterations as possible.

这适用于具有C#后端的Web应用程序。它的架构方式我无法将其中一个类导入到另一个类中直接调用该方法。不幸的是,我们的构建过程出了问题,因此我无法调试此代码,因此我希望尽可能少地进行迭代。

In one controller we have this method:

在一个控制器中我们有这个方法:

    [Route("api/uploadFile/{id}")]
    [HttpPost]
    [CustomAuthorize]
    [SwaggerResponse(HttpStatusCode.OK, Description = "File upload successful")]
    [SwaggerResponse(HttpStatusCode.InternalServerError, "Error uploading file")]
    public async Task<IHttpActionResult> PostFile(int id, [FromUri]bool replace=false)
    {
        //code to put the file in the database;
    }

and I need to figure out how to call that from a different controller. These two controllers are in two completely separate projects and have no knowledge of each other.

我需要弄清楚如何从不同的控制器调用它。这两个控制器分为两个完全独立的项目,彼此不了解。

I've tried a handful of variations of the following, but it each change takes about 8 mins in a build process so I didn't want to just hack on it anymore:

我尝试过以下几种变体,但每次更改在构建过程中大约需要8分钟,所以我不想再破解它了:

    HttpClient htc = new HttpClient();
    HttpContent content = new StreamContent(myfile);
    var response = await htc.PostAsync(this.Url.Content("~/api/uploadFile/9992"),  content);
    var responseString = await response.Content.ReadAsStringAsync();

1 个解决方案

#1


0  

Because it's all executing on the same server reflection could work.

因为它全部在同一服务器上执行,所以反射可以起作用。

First I would move the post file logic out into a separate method.

首先,我将post文件逻辑移到一个单独的方法中。

Then get a reference to the assembly using from there we just do this:

然后从那里获得对程序集的引用,我们就这样做:

Assembly assm = Assembly.Load("AssemblyName");
object instance = assm.CreateInstance("ClassName");
object retVal = instance.GetType().GetMethod("NewMethod").Invoke(instance, null); 

#1


0  

Because it's all executing on the same server reflection could work.

因为它全部在同一服务器上执行,所以反射可以起作用。

First I would move the post file logic out into a separate method.

首先,我将post文件逻辑移到一个单独的方法中。

Then get a reference to the assembly using from there we just do this:

然后从那里获得对程序集的引用,我们就这样做:

Assembly assm = Assembly.Load("AssemblyName");
object instance = assm.CreateInstance("ClassName");
object retVal = instance.GetType().GetMethod("NewMethod").Invoke(instance, null);