【发布时间】:2013-05-03 01:21:27
【问题描述】:
在独立(自托管)应用程序中,我希望有一个 httpserver,它在单个基本地址上可以提供简单的网页(没有任何服务器端动态/脚本,它只返回内容请求文件)或提供 RESTful 网络服务:
- 当
http://localhost:8070/{filePath}被请求时,它应该返回文件的内容(html、javascript、css、图像),就像一个普通的简单网络服务器一样 -
http://localhost:8070/api/后面的所有内容都应该充当普通的 RRESTful Web API
我当前的方法使用 ASP.NET Web API 来同时提供 html 页面和 REST API:
var config = new HttpSelfHostConfiguration("http://localhost:8070/");
config.Formatters.Add(new WebFormatter());
config.Routes.MapHttpRoute(
name: "Default Web",
routeTemplate: "{fileName}",
defaults: new { controller = "web", fileName = RouteParameter.Optional });
config.Routes.MapHttpRoute(
name: "Default API",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
WebController 是使用此幼稚代码为网页提供服务的控制器:
public class WebController : ApiController
{
public HttpResponseMessage Get(string fileName = null)
{
/// ...
var filePath = Path.Combine(wwwRoot, fileName);
if (File.Exists(filePath))
{
if (HasCssExtension(filePath))
{
return this.Request.CreateResponse(
HttpStatusCode.OK,
GetFileContent(filePath),
"text/css");
}
if (HasJavaScriptExtension(filePath))
{
return this.Request.CreateResponse(
HttpStatusCode.OK,
GetFileContent(filePath),
"application/javascript");
}
return this.Request.CreateResponse(
HttpStatusCode.OK,
GetFileContent(filePath),
"text/html");
}
return this.Request.CreateResponse(
HttpStatusCode.NotFound,
this.GetFileContnet(Path.Combine(wwwRoot, "404.html")),
"text/html");
}
}
同样,对于 /api 背后的所有内容,都使用普通 REST API 的控制器。
我现在的问题是:我在正确的轨道上吗?我觉得我在这里重建一个网络服务器,重新发明轮子。而且我猜可能有很多 http 请求网络浏览器可能会让我在这里无法正确处理。
但是,如果我想通过同一个基地址自托管并同时服务器 REST Web API 和网页,我还有什么其他选择?
【问题讨论】:
标签: web-services asp.net-web-api webserver