且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在.net core的剃须刀页面中设置全局变量?

更新时间:2023-02-14 18:11:47

HTTP请求通过客户端发送请求(包含标头和正文)。然后,您的服务器可以访问此信息并发送响应。这不会在服务器和客户端之间建立任何持久(持续)的连接。这意味着您的服务器与每个客户端之间没有永久链接。您声明的任何全局变量对于服务器的Web应用程序都是全局的,并且对于每个客户端都是通用的。

HTTP requests work by clients sending a request (with header and body) to your server. Your server can then access this info and send a response. This doesn't create any persistent (ongoing) connection between the server and client. This means there is no permanent link between your server and each client. Any global variable you declare will be global for your server's web application and will be common for every client.

您要在此处进行的操作是创建与每个客户端的连接隔离的变量。通常,这是通过 Session Cookie 变量完成的。但是在这种情况下,我看不出这将如何改善您编写的代码的性能。在您的代码中,您尝试从请求访问Http标头。 Cookie和会话变量的访问方式也非常相似。如果直接从标头中获取内容,则必须具有更好的性能。如果您要清理代码,而不必在每个页面上都编写代码,则服务可能会很有帮助。

What you are trying to do here is create variables isolated from each client's connection. Normally this is done with the help of Session or Cookie variable. But in this case, I don't see how this will improve any performance over the code you have written. In your code, you are trying to access the Http Headers from the request. Cookies and session variables are also accessed in a very similar way. If anything fetching directly from headers must have a slightly better performance. If you are trying to clean up your code so you don't have to write this on every page, services could be quite helpful.

您可以创建一个服务类,如下所示:

You can create a class for service something like this:

public class AgentChecker
{

    public bool IsIE { get; set; }

    // makes sure check is done only when object is created
    public AgentChecker(IHttpContextAccessor accessor)
    {
        string UA = accessor.HttpContext.Request.Headers["User-Agent"].ToString();
        if (UA.Contains("Trident") || UA.Contains("MSIE"))
        {
            IsIE = true;
        }
        else
        {
            IsIE = false; 
        }
    }

    // optional to simplify usage further. 
    public static implicit operator bool(AgentChecker checker) => checker.IsIE;

}

在启动类中添加以下内容:

In your startup class add the following:

// to access http context in a service
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// makes sure object is created once per request
services.AddScoped<AgentChecker>();

设置完成后,您可以使用:

Once this is set up, in your view you can use:

@inject AgentChecker checker

@* if you didn't create the implicit operator, you can use if (checker.IsIE) *@
@if (checker)
{
    <div>Is ie</div>
}
else
{
    <div>not ie</div>
}

注入您可以在任何视图页面的顶部使用它。尽管这仍然会在每个请求中创建一个新对象,但使用起来比较干净,无论您使用多少个局部视图,它都只会创建一个对象。

The inject goes at the top of any view page you would like to use this in. While this still creates a new object each request, it is cleaner to use and only creates one object no matter how many partial views you are using.