We have an angular page that accesses a restful web service we are also generating. For the website we are making the routes match those of the web service for simplicity. For example accessing the website at http://myserver.com/books/book/1/chapter/2 would access the same route in the web service.
Now the slightly tricky part, if a list of books was returned then each book would contain a link to itself.
"links": [
{
"rel": "self",
"href": "http://myserver.com/books/book/1"
}]
The problem is in web api we use Url.Link to generate the href value. This though gives the server address as the web service and not the requesting angular website. We want to use these references to auto generate links on the web page itself. But they obviously just link straight back to the web service.
Generated: http://myWebServiceServer.com/books/book/1
Ideal: http://myWebSiteServer.com/books/book/1
Is there any nice function like Url.Link that the correct server could be specified?
To quote Scott Allen, "technically, you shouldn't use the Url property in an api controller to generate non-webapi links". I'm no expert on producing restful webapi's but it doesn't seem like a good design if the routing of the returned url is dependant on the routing of the calling website. Shouldn't the api just return information regarding books etc and let the website construct its own urls based on that information.
Regardless, the Url.Link you stated that you are using always returns an absolute url (i.e. http://myWebServiceServer.com/books/book/1).
If you insist on returning a url you could use Url.Route which can produce a relative url (i.e. /books/book/1). Your calling website can then determine the server to be added to the url.
Related
I'm very new to web development but I wanted to create a web api for an existing Windows Service application I created for work.
My goal right now is to create a simple web app consisting of some text input fields where someone can enter their email and subscribe to a mailing list.
I was pointed in the direction of using OWIN to self-host a web api in my existing project so I looked at this guide to get started:
https://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
This guide shows the console app calling and displaying the API, but I wanted to do the same from a web app. So I tried to do what is accomplished here in the 'Getting Started with ASP.NET Web Api 2' guide using a console application with OWIN.
When I start my console application, I can enter http://localhost:8080/api/values/1 and I get <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">value</string> Which I assume means the web server is running and responds to the request to get my string value that I'm returning from my ValuesController.
However I've been trying to create a simple web page that calls the API to get the value but I haven't been able to figure it out.
Right now my index.html has the following in the body:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = "http://localhost:8080/api/values/1";
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
$('#value').text("done");
})
.fail(function (jqXHR, textStatus, err) {
$('#value').text('Error: ' + err);
});
});
</script>
And I just get Error: printed on the page. Again I'm new to working on web related technologies so any guidance would be much appreciated.
Ok so, following the discussion in comments (helping you to debug the app).
The cross-origin security policy in browsers restricts web pages from calling an data source that exists on a different domain. A domain is either a different url, or a different port at the same url.
http://localhost:80
is a different url/domain from:
http://localhost:81
There are two solutions to this, either utilise JSONP, or CORS to make the request to the api, JSONP basically wraps your json data up in a function call. When the api call returns, it executes the callback/function call, bypassing the security restriction.
However, both JSONP and CORS require server support, which brings solution 2...
Serve up the webpage you are trying to use from the API, meaning you server it from the same domain, hence no cross-domain issues!!
Glad you have got it sorted, I know it can be frustrating with web calls.
The case in hand is as follows:
User hits a control on a website, website calls an API.
API does some logic, and shall then construct a post http request and redirect to another site.
User should view the redirected site.
Alternative solution i guess is for the api to return an object that the website can use to redirect.
Your kind suggestions and ideas
You should take a look at the HTTP/1.1 Status Code Definitions. Specifically section 10.3 "Redirection 3xx". It describes the available status codes, and you should be able to find a suitable one.
Example: 303 See Other
Your API would create a response with status code 303 and add a "Location" header that contains the address of the site you redirect to.
What specifically in WebAPI responds to:
1. http://server/vroot/odata
2. http://server/vroot/odata?$metadata
3. http://server/vroot/odata/Foo
When #3 is requested, I understand that my 'FooController' responds as
configured in my WebApiConfig.cs.
But it is not clear to me how WebAPI responds to #1 or #2. How does it know
what to return? How is that response configured in my code?
UPDATE: Here is a HUGE clue
From http://blogs.msdn.com/b/webdev/archive/2013/01/29/getting-started-with-asp-net-webapi-odata-in-3-simple-steps.aspx
One important thing to realize here is that the controller name, the
action names, and the parameter names all matter. OData controller and
action selection work a little differently than they do in Web API.
Instead of being based on route parameters, OData controller and
action selection is based on the OData meaning of the request URI. So
for example if you made a request for
http://my.server.com/vroot/odata/$metadata, the request would actually get
dispatched to a separate special controller that returns the metadata
document for the OData service. Notice how the controller name also
matches the entity set name we defined previously. I’ll try to go into
more depth about OData routing in a future blog post.
]
returns you the Service Document
returns you the Service Metadata Document
WebAPI knows this because you add a route similar to config.Routes.MapODataRoute("ODataRoute", "odata", model);
Check out this detailed explanation: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/creating-an-odata-endpoint
I created REST base webAPI in MVC 4 and hosted on server when I call this from HTML on other domain and on my local pc I need to call it as JSONP request like put callback=? in url so it can be jsonp. My question is that why this is so? if its due to cross domain then how google and facbook and other companies host their api we also call it from our own domain but we dont keep callback=? in their url.
so why my API need callback=? in url if i call it from other domain or on my local pc with simple jquery html.
Its because of the Same Origin Policy imposed by the browsers.
See
http://www.w3.org/Security/wiki/Same_Origin_Policy
http://en.wikipedia.org/wiki/Same_origin_policy
.
Also note that CORS might be a better option than JSONP in the future
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
EDIT: ------------
If you have gone through above links you would see that JSONP allows users to work-around this Same Origin Policy security measure imposed by the browsers.
Trick is browsers allow tags to refer files in other domains than the origin.
Basically what happens is with JSONP, you send a callback function name to the server appended to the query string. Then the server will pad or prefix it's otherwise JSON request with a call to this function, hence the P in the name to denote response is padded or prefixed.
For example you can create a script tag like
then the target server, should send a response such that
mymethod({normal: 'json response'})
when this repsone is evaluated on the client side (as for any other javascript file) it will effectively call your method with the JSON response from that server.
However, this can only do GET requests.
If you want to make POST (PUT/DELETE) requests you need to use CORS in which server needs to set a specific header beforehand.
Access-Control-Allow-Origin: www.ext.site.com
Hope this helps.
Because of the same-origin policy limitations. The same-origin policy prevents a script loaded from one domain from getting or manipulating properties of a document from another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This basically means that the browser isolates content from different origins to guard them against manipulation.
Hey I am trying to use Purolator Web services to validate the address.
I already included web services in my project and have all credential to communicate but I don't know how to validate through web services and it's my first time that I am using web services please help
I am using C#
I have three input field to asp.net to validate
city
Postcode and
province
If someone can give me details info how to this validation through web service I will really appreciate their help.
Please give some sample code how can I do this
already included reference
using com.purolator.devwebservices;
com.purolator.devwebservices.ValidateCityPostalCodeZipRequestContainer;
This is how it show in their documentation.
I like to upload the picture to show you the web service request and response diagram but I don't have privileges
ValidateCityPostalCodeZipRequestContainer
ValidateCity PostalCodeZipRequest
tns:RequestContainer (extension)
tns:Addresses SenderA ddress - ShortAddress[]
tns:ArrayOfShortAddress
tns:ShortAddress
tns:ShortAddress
tns:City City -string
tns:Province Province - string
tns:Country C ountry - string
tns:PostalCode P ostalC ode; - string
In order to call the webservice, you first have to add a web reference, which you already did, now you need to instantiate the object of proxy class which from your post i believe is ValidateCityPostalCodeZipRequestContainer and call the RequestContainer method of object with required parameter to validate the address.
* Answer above is based on my assumptions becuase I don't have any information about the webservice. If you can post WSDL then I can give a precise answer.
Between, according to Purolator's website there are number of sample available here: https://eship.purolator.com/SITE/en/content/developmentprocess/websservicesprogram.aspx
May be you can find one using asp.net
And by the way there is a nice tutorial given here for consuming webservices in asp.net: Calling Web Service using ASP.NET.