简体   繁体   中英

How to call a microservice in .NET

I've created a very simple REST microservice that receives information about an email and sends it. The microservice send method looks something like this:

//EmailController
[HttpPost]
public IHttpActionResult Send(Email email)
{
    // send email via exchange
}

Now in my application, I call it using RestSharp like this:

var client = new RestClient("http://localhost:51467/api/");
var request = new RestRequest("email/send", Method.POST);
request.RequestFormat = DataFormat.Json;
dynamic obj = new ExpandoObject();
obj.FromAddress = from;
obj.ToAddress = to;
obj.Subject = subject;
obj.Body = body;

request.AddBody(obj);
client.Execute(request);

Questions I have:

  1. Is this the best way to do the call? Obviously i'll later have to add error handling etc, but I'm talking more the way I'm using RestSharp to do the call.

  2. I'm finding it a bit uncomfortable that my app needs to kind of know what object the microservice expects to receive - there's no sort of definition/interface/contract that it uses to know for sure. Is this generally accepted as being ok for REST or should I implement some sort of interface that my app has so it can call my microservice in a bit more of a defined way. Is that even something possible with REST?

Thanks for any help!

REST services do not have a schema or WSDL type of function to define the format of the service. This is what makes them more light weight compared to traditional web services.

There is something called WADL, or Web Application Description Language, but this is not really a standard, and isn't widely supported. It's also quite controversial as there are many that feel it's not needed.

http://en.wikipedia.org/wiki/Web_Application_Description_Language

Also see this discussion on Programmers

https://softwareengineering.stackexchange.com/a/133693/4368

I know this is super old but I couldnt help but answer for the sake of currency.

There are two ways of communicating an API contract with other .net services which I find particularly useful.

  • Ship a nuget package with the contracts (Interfaces describing responses) and possibly some call logic to methodise your api calls
  • Use swagger to describe your api (seems to have come out as the API description winner, Swashbuckle makes it seamless in .net) and then either hand code the bits you need at the caller or use a codegen

I quite often do both, swagger is also nice for documentation and other language compatibility, and its good practice to be formal about your contracts and backward compatibility.

I would use ASP.NET Web API client libraries. It works with any REST API, whether its coded using .NET or some other framework.

Look here for details: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Nuget package: Microsoft.AspNet.WebApi.Client

I typically don't bother with extra client Libraries like RestSharp. I feel that the purpose of REST is to stay as close to gold old HTTP as possible, negating the need for anything other than HttpWebRequest/Response. Working with the request/responses directly gives great control and encourages you to think about what's actually going on instead of abstracting everything away like you would with a traditional WCF or ASMX service.

For microservices I've built in the past I've kept the request and response objects within separate libraries and I've the distributed the source to other Developers within my organisation to give them a leg up in calling the service but it probably wouldn't be practical for external consumers; again I guess the point of going for a microservice over a full scale WCF service is that by their nature the request/responses being passed around are small and simple. I also felt a little uncomfortable with this practice at the start; however when I started getting really responsive web apps calling microservices with javascript (usually jquery) just as easily as traditional .NET ones I started seeing the potential for some really good integration of our internal systems. Eventually our intranets were providing actions and views into business applications that weren't possible previously.

HttpWebRequest webRequest = WebRequest.Create("http://localhost:51467/api/email/send") as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Credentials = CredentialCache.DefaultCredentials; //or account you wish to connect as
webRequest.PreAuthenticate = true;
webRequest.ContentType = "application/json"; // or xml if it's your preference

string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(requestObject);

using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
    streamWriter.Write(jsonData);
    streamWriter.Flush();
    streamWriter.Close();
}

HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;

if (webResponse.StatusCode != HttpStatusCode.Accepted)
    throw new ApplicationException("Unexpected Response Code. - " + webResponse.StatusCode);

string response;
using (System.IO.StreamReader readResponse = new System.IO.StreamReader(webResponse.GetResponseStream()))
{
    response = readResponse.ReadToEnd();
}

//swap out for regular xml serializer if you've used xml
dynamic responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(response);

Also another tip, if you're working with web api, I'd really suggest adding in the web api help pages and test client. You won't have the automatically generated wsdl you get with WCF and ASMX but you can get some really nice documentation about your microservice for other developers (even better in my opinion that auto generated proxy classes) and a test harness that lets to exercise the service from your browser

https://github.com/wuchang/WebApiTestClient https://www.nuget.org/packages/Microsoft.AspNet.WebApi.HelpPage/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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