Restful Web API from Browser - asp.net

I am using ASP.NET MVC 4 WEB API to create a Restful API service. This is my first go at it, so if you feel I am taking a wrong approach please feel free to correct.
I want to create a rest API (only & not a website, the consumer of the api can decide where they want to consume it), in the past I have used Restful WCF service to achieve this.
I have created a new ASP.NET MVC 4 Web Application and chose the WebAPI project template. I have added a controller class 'CatalogueController.cs' the purpose is on Get() operation I want to return the Catalogue list. The CatalogueDo contains only one property 'Service' of type string.
[System.Web.Http.HttpGet()]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, Catalogue);
}
When I run the application the browser loads with the URL http://localhost:5502/ resource not found, if I add the controller name http://localhost:5502/Catalogue/ the browser pops open a notepad with,
[{"Service":"Exchange"},{"Service":"Holidays"}]
The data is correct but
the browser keeps showing resource not found and after my request has been served the URL changes to http://localhost:5502/.
Question,
Am I doing something wrong? Should the response that pops up in the
notepad not be shown as xml in the browser it self?
Why does the controller name get removed from the URL once the request has been served?
Is it at all possible to invoke this REST service from Excel or Power Pivot?

Related

ASP.Net Web API - Extract header in common place

I am working on SaaS application where I have implemented ASP.Net Web API as a service layer. In my Web API, when any request generated, it will have one header value "x-companyid" which is company specific and identify request comes from which company (Tenant).
I require that companyID in all my ApiControllers in Web API project. Of course I can get header value in every ApiController by using "Request.Headers.GetValues("x-companyid") but it will be repeated in all ApiControllers.
I have tried to create "BaseApiController" and inherit all my ApiControllers from "BaseApiController" but it's not allowing me to override ActionExecuting so that I can extract header at common place.
Can anyone suggest how can I extract "x-companyid" header commonly in my project so that I don't have to repeat code in all ApiController?
Your Best friend are action filters.
as they intercept each api call for specific controllers.
All u had to do is to decorate the controler name with something u made like
[Tenant]
public foo MyController()
{}
this approach gives you controll over what controllers you wish to add this extract to happen becouse maybe youll need some lookup apis and stuff that dont need to be for a specific Tenant
here is a very Helpful link :
https://www.c-sharpcorner.com/article/filters-in-Asp-Net-mvc-5-0-part-twelve/
Update
since there is a only one company for each instance
i would recommend adding a singleton for the current tenant u can access that anyway
https://en.wikipedia.org/wiki/Singleton_pattern

Can we completely replace the functionality of MVC with api

I have recently started learning both .Core MVC and WEB api.I found that functionality of Web Api is similar to MVC,then why can't we use API instead of MVC for all cases of MVC
For example for returning a list of Pies from DbContext _dbcontext
Code:
Public IAction Index()
{
var PiesCollection=_dbcontext.Pies.ToList();
return View(PiesCollection);
}
Instead of returning the PiesCollection to a View,why can't we use AJAX from a view to call GetPies api and replace it with
public IAction GetPies()
{
return JsonResult(_dbcontext.Pies.ToList());
}
There's nothing stopping you from doing that, however, it comes with the downside of putting more work on the front end, and can cause some irritating side effects for users if you are not careful.
Rather than doing all the work building the HTML before sending it to the browser, you are sending them incomplete HTML with spaces left open for 'future' content. Then the page then has to request this missing content. The service has to do all the same work as before gathering the data, but now has to serialize it to send to the browser. Then the browser has to parse that content to build a the UI.
This can mean that the front-end is no longer coupled to your data so you can cache it or host it on other servers since it doesn't need all the logic in it. This is how some mobile apps work even. The front end isn't a website anymore, but an iOS or Android app, that gets all the data from the asp.net services.
But the downside is that if the UI is heavily driven by the data returned by that service, then your user has to wait for the browser/app to get the response, parse it, and render it onto the screen. This can be extra irritating for users when the contents of the page move or change as data loads in.

Call web service and passing a cookie in an ASP.Net Web Application

We have to call a web service hosted by our client. We were able to add a web reference to our ASP.Net web application and use the web service. The client just sent us a text file and said we need to pass this as a cookie to get access to the web service. I ask for their help and they sent me this.
SoapHttpClientProtocol clientProxy = new T();
clientProxy.CookieContainer.Add(uri, cookie);
Is there a way to do this using a web reference? Or do I hav eto make a soap call?
The web reference you have generated should be derived from System.Web.Services.Protocols.SoapHttpClientProtocol (for details see this link). The ancestors of this class also provide a property named CookieContainer so that you can use the following code:
webRefInstance.CookieContainer.Add(uri, cookie);

Difference between wcf and web api uri definition

I want to convert our existing WCF REST web services to ASP.NET Web APIso I started to look into it.
Getting one of my function (i.e. login) up and running in ASP.NET Web API was quite straight forward but there is one thing I'm confused about and I hope one of you can clarify this for me.
In our WCF REST web service, our login (POST) function was called as follows:
http://localhost/mywebsite/mywebservice.svc/Authentication/Login
We'd pass a LoginRequest to it and we'd get a LoginResponse back.
Now in ASP.NET Web API, I've our Login (POST) function is being called as follows:
http://localhost/api/authentication and I'm passing the same LoginRequest and I get the same LoginResponse.
My confusion is, how does ASP.NET Web API know to use the Login function which is defined in the AuthenticationController?
I assume it has something to do with the parameter type being passed but what if I have another function that has the same parameter type, how would it differentiate between the 2?
For example, what if I had a LocalLogin and CloudLogin (not the case btw) and both require the LoginRequest as an input parameter and both return the LoginResponse, how would it know which one to call since it's not part of the URI?
Thanks.

How Do I Get RouteData Values from a Web Service in .Net 4.0

I am trying to extract an id number from a URL using a web service so that it can be used as a parameter for a where clause in a select statement that produces data from a database based on the id number of a record. That data will then be passed back to the page to populate an element in a jQuery modal popup widow.
Everything works fine with a static id number (ex: string postid = "120"), but I don't know how to get the id number from the URL. I'm using Routing in .Net 4 and the method for accessing Routing in pages does not work in a web service. In pages I just do stuff like var id = RouteData.Values["id"]; and that gets the id, but when i did it in a web service I got an error:
CS0120: An object reference is required for the non-static field,
method, or property 'System.Web.Routing.RouteData.Values.get'
Summary:
I have web service accessed form a details page where I want to get RouteData for the page making the request. I want to do this just as easily as I can on a page using RouteData.Values which is just as easy as the now the obsolete Request.Querystring.
Now I am more confused because although I could easily add a new route for the web service I don't know I would call that using jQuery Ajax because of the webservice.asmx/webmethod syntax.
Right now I have URL: "../webservices/googlemaps.asmx/GetGoogleMap" in my jQuery Ajax, but that is not a real URL. It only exists in jQuery somewhere and the way to call the service using just JavaScript is no a real URL either, its webservice.webmethod() which in this case would be googlemaps.GetGoogleMap().
I will try registering a route for webservices/googlemaps.asmx/GetGoogleMap/postid, but I doubt it will work because GetGoogleMap is not a directory or a querystring.
Get current http request and use RequestContext property to get request context - it has current routing data. For example,
var id = HttpContext.Current.Request.RequestContext.RouteData.Values["id"];
In case of WCF based web service, make sure that service is participating in ASP.NET pipeline (see ASP.NET Compatibility)
EDIT: Sorry for misleading answer - the above will not work unless web service url is registered in routing engine. However, it may not solve your issue of retrieving the id - what kind of service implementation are you using? Are you making a GET request or POST request? Typically, web service handler (asmx) or WCF pipeline should convert GET/POST parameters to method parameters. Post your web service code and how you invoke it.

Resources