我需要编写一个Web API方法,将结果作为CSS纯文本返回,而不是默认的XML或JSON,是否需要使用特定提供程序?ASP.Net WebAPI返回CSS
我试过使用ContentResult类(http://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.108).aspx),但没有运气。
感谢
我需要编写一个Web API方法,将结果作为CSS纯文本返回,而不是默认的XML或JSON,是否需要使用特定提供程序?ASP.Net WebAPI返回CSS
我试过使用ContentResult类(http://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.108).aspx),但没有运气。
感谢
您应该绕过内容协商这意味着你应该直接返回的HttpResponseMessage
一个新的实例,并设置内容和内容键入自己:
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(".hiddenView { display: none; }", Encoding.UTF8, "text/css")
};
只是说我认为这是值得使用重载的StringContent来指定内容类型为CSS StringContent(css,Encoding.UTF8,“text/css”) –
@MarkJones,好主意(否则它会服务器文本/平原没问题,但如你所说,最好使用text/css)。我已经编辑了相应的答案。 –
使用的答案here为灵感。你应该能够做到这样简单的事情:
public HttpResponseMessage Get()
{
string css = @"h1.basic {font-size: 1.3em;padding: 5px;color: #abcdef;background: #123456;border-bottom: 3px solid #123456;margin: 0 0 4px 0;text-align: center;}";
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(css, Encoding.UTF8, "text/css");
return response;
}
你可以返回一个HttpResponseMessage,获取文件并返回流?像这样的东西似乎工作....
public HttpResponseMessage Get(int id)
{
var dir = HttpContext.Current.Server.MapPath("~/content/site.css"); //location of the template file
var stream = new FileStream(dir, FileMode.Open);
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(stream)
};
return response;
}
虽然我想补充一些错误在那里,如果该文件不存在等检查....
而就堆在为乐趣,假设你将.css作为嵌入文件存储在与控制器相同的文件夹中,这里的版本可以在自主主机下工作。将它存储在你的解决方案中的文件是很好的,因为你获得了所有VS智能感知。而且我添加了一些缓存,因为这个资源的机会不会有太大的变化。
public HttpResponseMessage Get(int id)
{
var stream = GetType().Assembly.GetManifestResourceStream(GetType(),"site.css");
var cacheControlHeader = new CacheControlHeaderValue { MaxAge= new TimeSpan(1,0,0)};
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
CacheControl = cacheControlHeader,
Content = new StreamContent(stream, Encoding.UTF8, "text/css")
};
return response;
}
这是因为Web API和MVC是两个完全不同的框架,看起来非常相似。不幸的是,在封面之下他们非常不同。我之所以编辑数十篇文章来删除术语“ASP.NET MVC Web API”的原因之一,是因为它将每个人都认为它们是同一框架的一部分,并且框架的组件可以互换。 –