简体   繁体   English

从同一应用程序中的另一个WebAPI调用WebApi

[英]Call WebApi from another WebAPI in same application

I have several webAPIs developed in MVC WebAPI such as 我有一些在MVC WebAPI中开发的webAPI,例如

public IHttpActionResult SendBroadcast(FinalPayload FinalPayload)

And I want to call another web api from inside this API. 我想从此API内调用另一个Web API。 All my APIs are in the same application. 我所有的API都在同一个应用程序中。 The signature of the second API is 第二个API的签名是

public IHttpActionResult SendMessage(Notifications)

From the first API i tried 从我尝试的第一个API

this.SendMessage(Notifications)

and got error message something like reference to static object .... 并收到错误消息,例如对静态对象的引用。

I wanted to know if this way of calling webAPI is allowed or do I have to invoke a web client or similar such. 我想知道是否允许这种调用webAPI的方式,还是必须调用Web客户端或类似的客户端。

Any help in this will be much appreciated. 在这方面的任何帮助将不胜感激。

1st approach 第一种方法

You have to redesign the code in your application ie Solution. 您必须重新设计应用程序中的代码,即解决方案。

  • Create a class library project. 创建一个类库项目。 Create an interface for the logic/functions which are common and consumed by different projects. 为不同项目共用和使用的逻辑/功能创建一个接口。
  • Implement the interface in the class library project. 在类库项目中实现接口。
  • In different projects(ie WebAPI projects) use the interface to access the common functionality. 在不同的项目(即WebAPI项目)中,使用接口来访问通用功能。

2nd Approach 第二种方法

As thought by you, of-course you can create a web client to access the Web API in another project. 如您所想,您当然可以创建一个Web客户端来访问另一个项目中的Web API。

  • Its not a good design and your problem is not ACTUALLY solved (just circumvented). 它不是一个好的设计,并且您的问题没有得到实际解决(只是规避了)。
  • Poor efficiency, as webclient will use http request to access the code in same solution. 效率低下,因为Webclient将使用http请求来访问同一解决方案中的代码。
  • For future maintenance you may end up creating multiple web clients. 为了将来的维护,您可能最终会创建多个Web客户端。

No, as usual you'll need to create a new web client in order to consume the API. 不,通常,您需要创建一个新的Web客户端才能使用该API。

What @Marcus H has suggested in the comment is doable too, just wrap the logic inside second API into a separate method (be it instance or static) and invoke it from your first API will do the trick. @Marcus H在注释中建议的内容也是可行的,只需将第二个API内的逻辑包装到一个单独的方法(实例或静态)中,然后从第一个API调用即可。

Yes you can. 是的你可以。 You can create a webClient in your controller method method2 that calls method1. 您可以在调用method1的控制器方法method2中创建一个webClient。

This is a little helper class you could use to help you: 这是一个小帮手类,可以用来帮助您:

namespace Api.Helpers
{
    public static class ApiHelpers
    {
        private static string HttpGet(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            reader.Close();
            response.Close();
            return responseFromServer;
        }

        public static string HttpPostJson(string url, string json)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            };
        }
    }
}

If you want Cookie based authentication, then just use RestSharp instead. 如果您要基于Cookie的身份验证,则只需使用RestSharp。 If you use Postman the Chrome extension tool, then if you can access your endpoint, you can automatically generate your C# code. 如果使用Postman Chrome扩展工具,则可以访问端点,则可以自动生成C#代码。 Simply put the webclient code within the Controller method, and one API call will effectively chain to another. 只需将webclient代码放入Controller方法中,一个API调用即可有效地链接到另一个。

so in your ApiController you'd write something like: 因此,在您的ApiController中,您将编写如下内容:

IHttpActionResult method1() {
    var result = ApiHelpers.HttpGet("http://thing.com/test");
    return Ok(result);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM