Using JavaScript to connect to a .NET server

I have to use the resource using JS from our server. I installed the code below.

var targetUrl = "http://somePlace.com/actualResourceName"; var xdr = new XDomainRequest(); xdr.onload = function () { alert(xdr.responseText); } xdr.open("GET", targetUrl); xdr.send(); 

However, I do not understand how the method should be created on the other hand. I came up with the following sentence, fully aware that it was not working. For example, Iโ€™m sure that I donโ€™t have the required attributes. I'm not even sure where to set that the method should respond to actualResourceName ...

 [???] public String ActualResourceName() { return "Bye, bye, cruel word!"; } 

I googled around, but I did not find any solution. I could stumble upon him, not realizing that this is something useful.

How should a method be written in C #?

+4
source share
1 answer

Ok, here it is. I will describe two ways to do this, the simplest:

1. ASP.NET WebApi

You will need to create a new ASP.NET MVC4 project (whether release or RC), select "WebApi" as an option: Project startup

And you will have a ready-made template. Now you right-click the "Controllers" folder, then Add โ†’ Controller: enter image description here

and fill it out, for example. eg:

 public class ActualResourceController : ApiController { public string Get() { return "Hey there! Getting the resource..."; } } 

The default routes are in Global.asax, when you go to the definition of the WebApiConfig.Register(...) method, you will see that the default route is host/api/controller . Try this when you start the project and go over (in my case, the port is automatically selected by the development server) http://localhost:23030/api/ActualResource you will get:

 <string>Hey there! Getting the resource...</string> 

WebApi returns JSON or XML depending on the Accept header, if you want JSON to be single / standard, take a look at this link.

You can, of course, create a class and return it, it will be serialized for XML / JSON in the same way that you will see below with ServiceStack.


2. ServiceStack

ServiceStack is now a powerful open source open source REST web service. It works a little different than WebApi, and here's a brief introduction (although the documentation is good):

Create a regular ASP.NET MVC project (in my case MVC4) - you will have an empty template:

service stack startup project

Then start the package manager console and enter (for example, documentation) Install-Package ServiceStack.Host.Mvc , which will provide you with a ServiceStack project template with a training application, which you can delete later if you want.

But first, ServiceStack first works with the DTO, Request-Response objects. So create them, the ActualResource class, which will serve as the request, and the ActualResourceResponse , which will be the answer. Since you have no parameters in the query, the first one is trivial:

 public class ActualResource { } 

Any parameters will be automatic properties. Now the answer:

 public class ActualResourceResponse { public string ResourceName { get; set; } } 

And the service class itself:

 public class ActualResourceService : Service { public object Get(ActualResource request) { return new ActualResourceResponse { ResourceName = "Hi! It the resource name." }; } } 

You could, of course, return without string for your current goals, it would work anyway.

Now everything that happens in the AppHost.cs file is created in the ServiceStack template, let's take a look and change it a bit:

 Routes .Add<Hello>("/hello") .Add<Hello>("/hello/{Name*}") .Add<Todo>("/todos") .Add<Todo>("/todos/{Id}") //everything up to here are a template/tutorial routes, you can safely remove them .Add<ActualResource>("/actualResource"); //and here you add a route to your own service 

For it to work, you need to go to Global.asax and comment out the entire line of WebApiConfig.Register(GlobalConfiguration.Configuration) , then go to the RouteConfig.RegisterRoutes method and add:

  routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("api/{*pathInfo}"); // <<<---- this line routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 

It takes a little more plumbing, but it's still not bad.

Now, when you start the service, go to localhost:whateverport/api/actualResource , you will get a familiar string, and here is a screenshot: ServiceStack reply page

ServiceStack can be serialized in various formats, so if you go to http://localhost:yourPort/api/actualResource?format=json , you will get:

 {"resourceName":"Hi! It the resource name."} 

if ?format=xml , then:

 <ActualResourceResponse> <ResourceName>Hi! It the resource name.</ResourceName> </ActualResourceResponse> 

And so on...

Setting up ServiceStack is now a little more complicated, but it supports, for example. Memcache out of the box, you can drop it on Redis, you can use various authentication providers, all of which can be very useful in some scenarios. But, as Uncle Ben once said, "great responsibility comes with great power," and the phase is even more difficult to establish ...


Now you can choose what you want, these two are the simplest options right now IMHO. Of course, this is just a simple tutorial to get you started, you will have the opportunity to study this topic in detail when you move on to the project.

+5
source

Source: https://habr.com/ru/post/1445051/


All Articles