为什么我不应该 return HTML 来自 ASP.NET ApiController?
Why shouldn't I return HTML from an ASP.NET ApiController?
查看自托管 OWIN 应用程序的教程,这些教程都指向使用 ApiController。此代码有效:
public class MapController : ApiController
{
// Get /map
public async Task<HttpResponseMessage> Get()
{
return await Task.Run(() => {
string html = File.ReadAllText("./Client/html/MapExample.html");
HttpResponseMessage response = new HttpResponseMessage
{
Content = new StringContent(html)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
});
}
}
这似乎有效...为什么我要扩展 Controller
与 ApiController
?
就 OWIN 库而言,我实际上无法访问 Controller
class...
从功能上讲,从 API 控制器返回 Html 没有任何问题。
您不想这样做的唯一原因是因为惯例是 API 控制器用于公开服务功能,而 ASP.NET MVC 控制器用于提供网站或页。
因此,一些开发人员会对这种方法感到困惑。
查看自托管 OWIN 应用程序的教程,这些教程都指向使用 ApiController。此代码有效:
public class MapController : ApiController
{
// Get /map
public async Task<HttpResponseMessage> Get()
{
return await Task.Run(() => {
string html = File.ReadAllText("./Client/html/MapExample.html");
HttpResponseMessage response = new HttpResponseMessage
{
Content = new StringContent(html)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
});
}
}
这似乎有效...为什么我要扩展 Controller
与 ApiController
?
就 OWIN 库而言,我实际上无法访问 Controller
class...
从功能上讲,从 API 控制器返回 Html 没有任何问题。
您不想这样做的唯一原因是因为惯例是 API 控制器用于公开服务功能,而 ASP.NET MVC 控制器用于提供网站或页。
因此,一些开发人员会对这种方法感到困惑。