Coming form the Autorest world, where the Web Client would generate one class per controller, but doesn't seem possible in NSwag using Service Reference within .Net 5
AutoRest generated web clients follow this pattern.
{BaseWebClient}.{ControllerName}.{Methods}
For example:
IWebClient webClient = new WebClient();
webClient.Employee.Get()
In NSwag, it generates all the methods under one class.
webClient.Employee_get();
Can somebody confirm if this is the new way or proper way of generating web clients?
Related
I'm new to asp.net mvc and web api. I'm reading a book which says:
ASP.NET MVC uses: System.Web.HttpRequest
and Web API Equivalent is System.Net.Http.HttpRequestMessage
and below is a picture that describes the request and result flow of web api
So my question is, how does hosting environment(which will typically be IIS) know that it should create a HttpRequestMessage object to represent the request from the client? I mean if the application is a MVC application, IIS should create a HttpRequest object instead of HttpRequestMessage, so how does IIS know which one to create?
As you can see from the picture you posted, the HttpRequestMessage exists only inside the "hosting" environment, web browser client does not know anything about that.
In the "hosting" world, IIS app pool is running the code you have built and deployed which knows very well wich framewok you are using as your code also contains the using assemblies you listed, System.Web... or System.Net...
Consider that even if you have shown separation between hosting, Controller and Action, all of that is running in same App Pool in IIS which, again, runs your code so knows what it is about as your IL assemblies were built from your specific source code.
I am not sure if I understand your question but this might be what you're looking for:
I mean if the application is a MVC application, IIS should create a
HttpRequest object instead of HttpRequestMessage, so how does IIS know
which one to create?
You must remember how you differentiate between a normal MVC Controller and a Web API Controller...
WebAPI Controllers enforces this annotation [ApiController] and must inherits from ControllerBase:
[ApiController]
public class PeopleController : ControllerBase {
//Your API methods here
}
A normal MVC Controller only inherits from Controller base class:
public class PeopleController : Controller {
//Your Action methods here...
}
Those already create configuration for your APP which becomes easier for you Hosting environment to know what is going and what to return when.
I hope you find this helpful.
I'm trying to consume the Swagger sample Petstore definition .json file at -
https://github.com/OAI/OpenAPI-Specification/blob/master/examples/v2.0/json/petstore.json
I used VS 2017 > Add > Add REST Api Client functionality. The import is successful and the Swagger Petstore proxy classes are successfully generated and added to my project.
Now I want to write C# code that is actually able to call the Petstore API.I'm unable to find any concrete examples that leverage the proxy classes above.
The way I have worked with REST services has been using the Web Client class in C# -
string sendText = "abc";
WebClient client = new WebClient();
c.Headers[HttpRequestHeader.ContentType] = "text/xml";
result = c.UploadString(url, sendText);
How do I write code that calls the PUT GET POST etc. operation on the Pet Store API?
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to retrieve the content of a JSON feed. I want to use HttpClient for downloading the content. For this purpose I've created a WEB API controller with a Get method which consumes the external API with HttpClient and then returns a List of deserialized content:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("externalAPI");
MediaTypeWithQualityHeaderValue contentType =
new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
HttpResponseMessage response = await client.GetAsync(client.BaseAddress);
string content = await response.Content.ReadAsStringAsync();
List<MyClass> data = JsonConvert.DeserializeObject<List<MyClass>>(content);
return data;
}
Now I'm going to show this list in client side using Angular and I know how should I do these steps but my question is why should I use a WEB API to consume another external API since I can simply use Angular HttpClient to consume that external API? Is using this WEB API to consume an external API and then return a List to Angular considered as best practices? If no, what is the best way, if I have to use MVC for this purpose?
In my project I consumed external API (which retuns json data), via webapi.
I did it because than my Angular project only have to maintain reference to webapi only i.e. just one url only. and another case in my project is external api url change in Dev,UAT and prod evironment, so i dont want to maintain in my angular project.
So I did it for two reason
Dont want to maintain reference of external api (i.e. URL of external api), and I get only one contact for getting data in my project which is my webapi
URL of external API change in Dev, UAT and PRod so I dont want to maintain that information in my Angular project.
That makes my code of angular more maintainable as if someone else look my code he/she get info that webapi is only location where they should look for ,from where data is coming
Imagine scenario where you are geting data from more then one external API, in that case you have to maintain reference to all API in your Angualr project. So Better to Follow FACADE design pattern, and keep only one point (which WebAPI in this case) which connect with all external api and returns data.
For getting data every 10 min you need to make use of RxJs
var timer$ = Rx.Observable.interval(1000) // 1000 = 1 second
timer$
.subscribe((v)=> this.Service.CalltoExtnerlAPIToGetdata()
.subscribe(data=> this.values = data));
please do unsubscribe from Rxjs Timer when you are not going to consume it to avoid memory leak.. http://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables
Let's say this external API is in the domain abc.com and your app is in the yourapp.com. If abc.com doesn't allow CORS (cross origin request), you won't be able to retrieve data from your angular app that is running in yourapp.com, so buildind a "middleware" in a server might solve this problem.
Anyway, it's not mandatory to build this middleware. If the target API allows CORS, there is no need to do this, and you can write the layer that requests data in your angular app.
The main reason lies within the same origin policy where a given origin, e.g. script executed by your browser, is only allowed to perform requests to an origin which is in the same domain (schema, host and port).
Reasons are mainly security related and have been extensively discussed in this StackExchange question.
A typical approach in MVC implementations to comply to this policy is to perform the HTTP request to your WebAPI using server side code, i.e. from the Controller using HttpClient. Then the Javascript from your View would simply call your Controller's method to retrieve the result.
As a side note, this approach has also the benefit of let you handle any serialization work in your Controller before presenting the data back to the View.
I'm new to Web Services from C#, but have worked C# for years, just never needed to use Web Services. Due to privacy issues, I can't disclose actual URL, but there is a test server and a production server where the web services are identical in all other respects, and the services were written / managed by another entity.
https://LiveSite.SomeDomain.com/FolderInWebSite/TestWebServiceSoapHTTP
and
https://TestSite.SomeDomain.com/FolderInWebSite/TestWebServiceSoapHTTP
Do I need to create two separate web references to the project and create different instances of them to go, or can I via some property just change which URL version it is sending data to.
Additionally, not being familiar working web services, I see the classes as Visual Studio imported. I can create instances of the classes and set the applicable properties (int, dates, strings, string[] arrays, etc). But not seeing how to actually say ... Go send it now. and then getting the response back.
I've done this from an older application with another language and was doing direct with HTTP and SOAP where I was able to make my own connection to the URL, build the body of the SOAP message, then send it.
Just use the "Url" property.
var myProxy = new MyProxy();
myProxy.Url = "http://foo.com/myservice";
Edit for second part of the question:
There should be a method for each action exposed the API that you can call. For example if the API exposes a MyAction that takes a string, the code generator should have generated a method that you can use like so:
myProxy.MyAction("hello");
The ONLY argument I can see for SOAP WCF over REST (json) wcf is the fact that once my service is created I can add a a reference in visual studio and I get a load of strongly typed classes ready for me and a client class that I can call all my webmethod through. It even sets up the web.config as far as I remember.
However when I expose a REST (json) service I still get a WSDL. So Im wondering is there still a way to build my references automatically?
Not using WCF tools. Unlike with SOAP (which has an established protocol for describing services - WSDL), REST doesn't. WADL is one such protocol, but it isn't too widespread and WCF does not support it. You still get a WSDL, because WCF will describe everything it can from the service. However, the WSDL won't have a <wsdl:port> element, which would describe the REST endpoint, which is why you get the WSDL, but cannot generate a reference to it.
The post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/03/26/mixing-add-service-reference-and-wcf-web-http-a-k-a-rest-endpoint-does-not-work.aspx has a lot more info on this issue.
Very old question, newer answer.
today using openapi (swagger) I can achieve this by using swagger inspector doing samples i can document my rest services as well as create a spec yml/json file allowing for validations and acceptance criteria as well as automated clients for java,python,c#,ruby,javascript and others I'm sure
I would like top elaborate:
Although it is true you cannot get a WSDL add service reference with a JSON REST WCF service, what I do is create two met data hooks:
is the operations returning JSON
is a single XML op returning a class wrapper which includes all the service classes I allow, I call it Discover:
i.e.
public class Discover
{
public Manager Manager {get;}
public Employee Emp {get;}
....
}
[OperationContract]
public Discover DiscoverDTOs()
You can, indirectly. While the client generated by Visual Studio won't work, that client implements an interface, also generated, that you can use like this:
WebChannelFactory<IService> factory = new WebChannelFactory<IService>(new Uri(endpointAddress));
IService proxy = factory.CreateChannel();
int result = proxy.Operation(1, 2, 3);
WebChannelFactory has another overload which accepts a WebHttpBinding, you can configure based on the service configuration, or you can make this configuration manually in your app.config file.