好的,就这样吧。我将描述完成它的两种方法,最简单的方法:
1. ASP.NET WebApi
您必须创建一个新的 ASP.NET MVC4 项目(无论是发布版还是 RC),选择“WebApi”作为选项:
您将准备好模板。现在您右键单击“控制器”文件夹,然后
添加 -> 控制器:
并填写例如像这样:
public class ActualResourceController : ApiController
{
public string Get()
{
return "Hey there! Getting the resource...";
}
}
默认路由在 Global.asax 中,当你去定义WebApiConfig.Register(...) 方法时,你会看到默认路由是host/api/controller。
让我们尝试一下,当您启动项目并进入(在我的情况下,端口由开发服务器自动选择)http://localhost:23030/api/ActualResource
你会得到:
<string>Hey there! Getting the resource...</string>
WebApi 根据 Accept 标头返回 JSON 或 XML,如果您希望 JSON 成为唯一/默认值,请采用 a look at this link.
您当然可以创建一个类并返回它,它将以类似于下面使用 ServiceStack 看到的方式序列化为 XML/JSON。
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
{
}
任何参数都是自动属性。现在回复:
public class ActualResourceResponse
{
public string ResourceName { get; set; }
}
还有服务类本身:
public class ActualResourceService : Service
{
public object Get(ActualResource request)
{
return new ActualResourceResponse {
ResourceName = "Hi! It's the resource name." };
}
}
您当然可以为您当前的目的返回裸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
为了让它工作,你必须去 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 }
);
需要多一点管道,但还不错。
现在当你启动服务时,进入localhost:whateverport/api/actualResource,你会得到熟悉的字符串,下面是截图:
ServiceStack可以序列化成各种格式,所以如果你去http://localhost:yourPort/api/actualResource?format=json下,你会得到:
{"resourceName":"Hi! It's the resource name."}
如果?format=xml,那么:
<ActualResourceResponse>
<ResourceName>Hi! It's the resource name.</ResourceName>
</ActualResourceResponse>
等等……
现在 ServiceStack 设置有点复杂,但它支持例如Memcache 开箱即用,您可以在 Redis 中使用,可以使用各种身份验证提供程序,所有这些在某些场景中可能非常有用。但是,正如本叔叔曾经说过的,“权力越大,责任越大”,而且设置阶段有点困难......
现在你可以选择任何你喜欢的,这两个是目前最简单的选择,恕我直言。当然,这只是一个简单的入门教程,当您开始项目时,您将有机会深入探索这个主题。