Question

I want to transition an existing website to a SPA with REST support from WebApi 2. I don't want to have the services be part of my existing project but I would like to be able to make requests from JavaScript to my Web API layer. It would be nice if I could use api.mywebsite.com but browsers will block the cross domain request.

Instead, I am assuming I'll have to add something to hijack a specific route like: mysite.com/api/*. What is the correct way of doing this? I can't seem to find any resources that talk about doing something like this.

I am trying create something like this with a single page application. I want to call directly into the web api from my client though.

.net framework orginization

Was it helpful?

Solution

If you want to separate Service and application you have a few choices:

  1. Use JSONP. It only supports GET requests. It can work if your application does occasional GET requests to some public api (like twitter), but it's not good for data-centric application with many Restfull or RPC style requests.

  2. Use CORS. It is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. One drawback of this option is that it supports only IE10+. See more CORS browse support. Enabling Cross-Origin Requests in ASP.NET Web API.

  3. Separate you application and service, but host them under the same domain.

OTHER TIPS

So, you have your WebAPI on one domain and your single page app on another. Here is an example of how you can call your WebAPI actions from the single page JS app.

WebAPI

public Book GetBook(int id)
{
    Book book = _repository.Get(id);
    if (book == null)
    {
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));`
    }
    return book;
}

Above is your WebAPI method. I am assuming you already have all of that taken care of. Below is the AJAX code that will call your API method.

$.ajax({
    url: 'http://myurl.com/<controllerName>/GetBook',
    type: 'GET',
    dataType: 'jsonp',
    success: function (data) {
        alert(data.msg);
    }
})

I believe that is all you will need. You can use Fiddler to view the data exchange. The output will be in JSON.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top