使用JavaScript连接到.NET服务器

4 javascript c# web-services

我应该使用我们服务器上的JS来获取资源.我已经设置了下面的代码.

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

但是,我不清楚需要如何创建另一方的方法.我已经提出了以下建议,完全意识到它不起作用.例如,我确定我错过了正确的属性.我甚至不确定该方法应该在哪里设置actualResourceName...

[???]
public String ActualResourceName()
{
  return "Bye, bye, cruel word!";
}
Run Code Online (Sandbox Code Playgroud)

我已经google了,但我没有找到任何解决方案.我可能偶然发现它并没有意识到它是有用的东西.

如何编写C#中的方法?

Pat*_*iek 5

好的,这就是它.我将描述两种方法来完成它,最简单的方法:

1. ASP.NET WebApi

您将不得不创建一个新的ASP.NET MVC4项目(无论是发布还是RC),选择'WebApi'作为选项: 项目启动

你准备好了模板.现在右键单击"控制器"文件夹,然后单击"添加" - >"控制器": 在此输入图像描述

并填写出来,例如:

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

默认路由在Global.asax中,当你去定义WebApiConfig.Register(...)方法时,你会看到默认路由是host/api/controller.让我们尝试一下,当你启动项目并进入(在我的情况下,端口由开发服务器自动选择)时,http://localhost:23030/api/ActualResource 你会得到:

<string>Hey there! Getting the resource...</string>
Run Code Online (Sandbox Code Playgroud)

WebApi根据Accept标头返回JSON或XML ,如果您希望JSON是唯一的/默认值,请查看此链接.

您当然可以创建一个类并返回它,它将以类似的方式序列化为XML/JSON,您将在下面看到ServiceStack.


2. ServiceStack

现在,ServiceStack是功能强大的开源REST Web服务框架.它的工作方式与WebApi略有不同,这里有一个快速介绍(尽管文档很好):

创建常规的ASP.NET MVC项目(在我的例子中,MVC4) - 你将有一个空模板:

服务栈启动项目

然后启动软件包管理器控制台并输入(如文档所示)Install-Package ServiceStack.Host.Mvc,它将为您提供一个带有教程应用程序的ServiceStack项目模板,如果您愿意,可以在以后删除.

但首先,ServiceStack适用于DTO,即Request-Response对象.所以让我们创建它们,这个ActualResource类将作为一个请求ActualResourceResponse,它将作为一个响应.由于请求中没有参数,因此第一个参数很简单:

public class ActualResource
{
}
Run Code Online (Sandbox Code Playgroud)

任何参数都是自动属性.现在响应:

public class ActualResourceResponse
{
    public string ResourceName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

而服务类本身:

public class ActualResourceService : Service
{
    public object Get(ActualResource request)
    {
        return new ActualResourceResponse {
           ResourceName = "Hi! It's the resource name." };
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以根据string当前目的返回裸机,它可以完全相同.

现在在ServiceStack创建的模板中,所有内容都发生在AppHost.cs文件中,让我们看看并稍微修改一下:

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
Run Code Online (Sandbox Code Playgroud)

要使它工作,你必须转到Global.asax并注释掉整WebApiConfig.Register(GlobalConfiguration.Configuration)行,然后进入RouteConfig.RegisterRoutes方法并添加:

 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 }
  );
Run Code Online (Sandbox Code Playgroud)

需要更多的管道,但它仍然不错.

现在当你启动服务时,进入localhost:whateverport/api/actualResource,你会得到熟悉的字符串,这是一个截图: ServiceStack回复页面

ServiceStack可以序列化为各种格式,所以如果你进入http://localhost:yourPort/api/actualResource?format=json,你会得到:

{"resourceName":"Hi! It's the resource name."}
Run Code Online (Sandbox Code Playgroud)

如果?format=xml,那么:

<ActualResourceResponse>
    <ResourceName>Hi! It's the resource name.</ResourceName>   
</ActualResourceResponse>
Run Code Online (Sandbox Code Playgroud)

等等...

现在ServiceStack设置有点复杂,但它支持例如开箱即用的Memcache,你可以在Redis中使用,你可以使用各种身份验证提供程序,所有这些在某些情况下可能非常有用.但是,正如本叔叔曾经说过的那样,"强大的力量带来了巨大的责任",并且设置阶段更加困难......


现在你可以选择你想要的,这两个是现在最简单的选择恕我直言.当然,这只是一个简单的教程,可以帮助您入门,当您开始使用该项目时,您将有机会深入探讨这个主题.