REST help page and REST Test client in MVC4 WebApi - rest

I developed several REST services using an early version of webapi (0.6.0), and for My services I enabled help page and Test client in as below in RegisterRoutes (called from application_start:
routes.Add(new ServiceRoute("auth",
new HttpServiceHostFactory()
{
Configuration = new HttpConfiguration()
{
EnableTestClient = true,
EnableHelpPage = true
}
},
typeof(Auth_Api)));
So I was able to access service at
http://<myserver>/auth
and access help page and test client at
http://<myserver>/auth/help
http://<myserver>/auth/test
Now I need to migrate them to MVC4 webapi, and I would like to accomplish the same behaviour, regarding test and help page, but I cannot find how to do it.
In RegisterRoutes I have this code which setup routes for API (REST) functionality
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Can I add System.ServiceModel.Activation and Microsoft.ApplicationServer.Http.Activation assemblies to MVC4 webapi app and set the routes as before?
Any drawbacks if I do it this way (in case it works)?
Thanks

Look at the API Explorer for the ability to generate Help pages. I believe the Test client has been dropped for the moment. I think there are plans to bring it back. I don't remember exactly.

Related

How to write REST Web services in Laravel 5.2?

I am creating api for mobile app in laravel 5.2 version but now I am facing one problem. Problem is that in my routes.php I am created routes for my website. Now my question is if I start creating api for mobile for that I have to create new routes for mobile api Or I can use same routes for RESTapi also?
In Laravel 5.2 I have to add any webservices libraries or not? If yes, Please suggest me how to use RESTapi in Laravel 5.2? Please help.
My routes.php
Route::auth();
Route::get('/', 'Auth\AuthController#login');
Route::get('admin/users', 'UserController#getUsers');
Route::get('admin/users/add', 'UserController#addUser');
If your routes an their inside logic returns json response, Its not necessary to create new routes, But if your routes does not returns json response, you must write new routes.
For having better APIs, json-hal, jsend or json-api conventions may help you.
Your api routes can coexist with your regular web routes. It's customary, however, to separate them, typically by a subdomain (https://api.yoursite.com), or at least a path (https://yoursite.com/api/v1).
Also, api version number is often included, as in my last example.
As for a package to develop apis in Laravel, have a look at Dingo. It's very complete, provides its own router, versioning, security, etc.
You have different middleware in laravel. By default you should have "web" middleware activated. It is either directly in your routes.php, in your controler constructor OR in the RouteServiceProvider.php
You wouldn't use web middleware for an api / restful service, therefore you should use another middleware ( e.g. "api" middleware which throttles requests to only allow max. 60 requets per minute etc. )
Typically you group your api requests
Route::group(['prefix' => 'api/v1'], function()
{
...
}
to strictly divide them from your application. You can then also easy change to v2 for example if you plan many releases
Update
if your api logic follows your business logic then you could aswell just watch for ajax calls and return json
public function index(Request $request) {
// do stuff here
if($request->ajax()) {
// return json
}
// return view
}

LightSwitch 2013: Calling the OData ApplicationData.svc service with forms authentication

I have written a simple LightSwitch 2013 application that manages "customers" by adding a customer entity and let LightSwitch handle the attached SQL Server file.
LightSwitch exposes the data with a restful service (ApplicationData.svc) that can be called like this:
https://somesite.azurewebsites.net/ApplicationData.svc/Customers
Now, I want to add another Windows 8 Universal App client application (Store and Phone), aside to the "included" HTML and Silverlight Desktop client. Therefore, I need to call the restful service programatically.
I struggle there with the forms authentication that I have enabled. So I try to log in programatically by code. I do not exactly know what is going on, I tried to analyze the traffic on the wire with fiddler. I see that there is a "LogIn.aspx" page called (GET), then a postback with the credentials filled out by the user is made (POST).
I always get an "401 - unauthorized" response.
My best guess looks like this:
var cookieContainer = new CookieContainer();
var clientHandler = new HttpClientHandler { CookieContainer = cookieContainer };
using (var client = new HttpClient(clientHandler))
{
client.BaseAddress = new Uri("https://somesite.azurewebsites.net");
// Get the login page
var loginGet = client.GetAsync("/LogIn.aspx").Result;
loginGet.EnsureSuccessStatusCode();
// Post-back to login page with credentials
var loginPost = client.PostAsync("/LogIn.aspx", new FormUrlEncodedContent(new Dictionary<string, string> {
{ "LoginUser$Username", "myname" },
{ "LoginUser$Password", "mypw"},
{ "LoginUser$LoginButton", "LOG+IN" },
})).Result;
loginPost.EnsureSuccessStatusCode();
// try to get the customers list via OData
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Getting a "401 - unauthorized" here:
var response = client.GetAsync("ApplicationData.svc/Customers").Result;
response.EnsureSuccessStatusCode();
}
Could someone kick me into the right direction?
PS:
I know that if I wrote an .NET client, I could just use the "Lightswitch.ApplicationData" class to call the restful service seamlessly. This solution is suggested here:
authenticate Lightswitch Odata service that uses forms authentication
But in my case, I have a Windows 8 Universal App, so I cannot reference the "Server" assembly generated by LightSwitch, which is based on the .NET runtime.
So I finaly found it .... I was completely wrong by handling around with cookies ....
A lightswitch OData service with Forms authentication is exposed with Basic Authentication.
https://usernamme:password#somesite.azurewebsites.net/ApplicationData/Customers
Be sure that you are using SSL of course!
See this article: Exposing LightSwitch Application Data

Can grails application have RestController and normal controller (for GSP) for same domain class

Recently I need to create REST API for existing grails application.
I am thinking that is it really possible to have both of the controllers (Normal and Restful) for same domain class in one single grails application?
Which controller will handle the request if make a HTTP GET request?
Please discuss your thoughts or if it is possible at all please guide me how.
We can define a new Controller to handle to REST API calls. e.g. In my app I have User as Domain Class and have UserController which return the data to GSP pages. I wanted to add REST API support (unfortunately) in the same app and I don't wanted to deal with mess it is already there in UserController. So I added new Controller UserRestController which will specifically handle the REST API calls and following mapping in UrlMappings.groovy which now works fine. Thanks to #codehx for helping me on this.
"/api/users"(controller: "userRest", parseRequest: true) {
action = [GET: "list", POST: "save" }
"/api/users/$id"(controller: "usersRest", parseRequest: true) {
action = [GET: "show", PUT: "update", DELETE: "delete"] }
Which controller will handle the request if make a HTTP GET request?
As far as it is not possible to have two controllers with same name in grails app this will not be confusing.
Just use two different names for Normal controller and for your RESTFUL controller, so obviously the URL for accessing the two urls will be different.

Linking to an MVC Route from Web API inside an in-memory server

I'm having problems testing the generation of MVC Routes from inside Web API. The code works when hit manually, but fails under test as the in-memory instance of Web API is unaware of the MVC routes and I can't figure out how to add them.
Here's an example project on github illustrating the problem, but I'll include some relevant code here.
I'm using an in-memory HTTP Server to host the Web API for integration testing:
private HttpConfiguration _config;
private HttpServer _server;
private HttpMessageInvoker _client;
[TestInitialize]
public void TestInitialize()
{
_config = new HttpConfiguration();
WebApiConfig.Register(_config);
_server = new HttpServer(_config);
_client = new HttpMessageInvoker(_server);
}
In my Web API Controller I'm trying to return links via the out-of-the-box default routes, both Web API and Mvc:
[HttpGet]
[Route("MvcRoute")]
public string MvcRoute()
{
return Url.Link("Default", new {Controller = "Other", Action = "Index"});
}
[HttpGet]
[Route("ApiRoute")]
public string ApiRoute()
{
return Url.Link("DefaultApi", new {Controller = "Example", Id = "MvcRoute"});
}
A test for the ApiRoute passes, but this test for the MvcRoute fails with the error message "A route named 'Default' could not be found in the route collection.":
[TestMethod]
public void ShouldReturnMvcRoute()
{
using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/example/mvcroute"))
{
using (var response = _client.SendAsync(request, CancellationToken.None).Result)
{
var responseContent = response.Content.ReadAsStringAsync().Result;
Assert.AreEqual("\"http://localhost/Other\"", responseContent);
}
}
}
So how can I make the in-memory server aware of MVC's routes? Or if that's the wrong question to ask, how can I run automated tests on a build server (i.e., no IIS) that hit Web API routes that generate links to MVC routes?
In-memory scenario is only supported in Web API. When hosted on a real server like IIS, Web API registers its routes onto the route table provided by System.Web.Routing.RouteCollection...Since MVC also registers its routes into this same route table, when generating links from Web API to MVC, the routes are indeed there...
Note that Web API came later than MVC and one of the design goals of it was to run outside IIS host (like it can be run on Selfhost too) and not have dependency on System.Web...In your about example, you are instantiating HttpConfiguration which means that you are having a different route collection where as in the real app WebApiConfig.Register would be passed in GlobalConfiguration instance...

Asp.net Web API RouteTemplate for passing multiple parameters to a method

I am using the ASP.Net Web API and I need to pass in a different number of parameters to the accions in my controllers, but I haven't found (I'm new to Web API) a specific way to indicate a route template for the different methods I might have in my controllers.
Currently I have this template.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I don't think I'll have to indicate a new template for each of the different methods I have in my controllers, do I?
As I told you, I'm really new to Web API and I haven't found much info about this , that's why I'd really apreciate if you could give me some advice or guidance.
EDIT
It seems that the best way to go will be passing in the parameters in the query string like this:
api/controller/action?parm1=val1&par2=val2&par3=val3
the problem is that I have no idea how to put this in a route template or how to retrive these values from the query string.
Take a look at using The Route Attribute.
Attribute Routing