您可以从 IHttpActionResult 派生自己的类型并执行此操作。
这篇文章谈到了它 - http://www.strathweb.com/2013/06/ihttpactionresult-new-way-of-creating-responses-in-asp-net-web-api-2/
您需要参考 RazorEngine - http://www.nuget.org/packages/RazorEngine/
在您的情况下,您可以创建一个从 IHttpActionResult 派生的 StringActionResult ,它执行类似于下面的操作。
public class StringActionResult : IHttpActionResult
{
private const string ViewDirectory = @"c:\path-to-views";
private readonly string _view;
private readonly dynamic _model;
public StringActionResult(string viewName, dynamic model)
{
_view = LoadView(viewName);
_model = model;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var parsedView = RazorEngine.Razor.Parse(_view, _model);
response.Content = new StringContent(parsedView);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return Task.FromResult(response);
}
private static string LoadView(string name)
{
var view = File.ReadAllText(Path.Combine(ViewDirectory, name + ".cshtml"));
return view;
}
}
然后在你的控制器中,做这样的事情。
public class MenuController : ApiController
{
[HttpGet]
public StringActionResult GetMenu([FromUri]string page, [FromUri]string menu)
{
return new StringActionResult("menu", new {Page: page, Menu: menu});
}
}