简体   繁体   English

Web API 2 的静态对象

[英]Static objects for Web API 2

i have a web api 2 project the client will request some data that is in a xml format.我有一个 web api 2 项目,客户端将请求一些 xml 格式的数据。 That XML will never change and i am wondering how i could keep it in ram so that it doesnt deserialize the xml each time it needs data from that file.该 XML 永远不会改变,我想知道如何将它保存在 ram 中,以便它不会在每次需要来自该文件的数据时反序列化 xml。

Would deserializing it at launch and then keep it in a static variable be the best way as it will only be use for reading ?在启动时反序列化它然后将它保存在静态变量中是最好的方法,因为它只会用于读取?

 [HttpPost]
 [Route("api/dosomething")]
 public string DoSomething() {

     var myData = XmlSerializer(MyDataStruct).Deserialize(something);
     return myDate;
 }

Here the xml is only used to communicate values to clients.这里 xml 仅用于向客户端传达值。 How can i make it so that i could deserialize it once and then return that directly.我怎样才能做到这一点,以便我可以反序列化一次,然后直接返回它。 Would using static member enable this feature ?使用静态成员会启用此功能吗?

A simple cache-aside approach with a static field could be a fair option:带有静态字段的简单缓存方法可能是一个公平的选择:

private static MyDataStruct _myData;

[HttpPost]
[Route("api/dosomething")]
public string DoSomething() {
    if(_myData == null)
    {
        _myData = new XmlSerializer(typeof(MyDataStruct)).Deserialize(something);
    }

    return _myData;
}

If you want even better performance and completely skip both the deserialization from your XML and the serialization of your response body into JSON/XML, then I strongly suggest you an HTTP output caching approach, using a library like this one: AspNetWebApi-OutputCache .如果您想要更好的性能并完全跳过从 XML 的反序列化和将响应正文序列化为 JSON/XML,那么我强烈建议您使用 HTTP 输出缓存方法,使用这样的库: AspNetWebApi-OutputCache

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM