4

Code Snippet: Conditional User Agent Logic with Blazor

 2 years ago
source link: https://codyanhorn.tech/blog/code-snippet-conditional-user-agent-logic-with-blazor
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
  • Blazor
  • Code Snippet
  • User Agent

Code Snippet: Conditional User Agent Logic with Blazor

10 Sep 2021

Below is a quick snippet of how to render your Blazor application without JavaScript, so when an bot comes in it will have less assets to deal with on the Request.

Snippet

The snippet uses a regex to match on some standard bot User Agents string. If the user agent does not match our bot regex it will include the JavaScript for Blazor Server.

@* _Host.cshtml *@

@page "/"
@namespace Example.Pages
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.Net.Http.Headers
@using System.Text.RegularExpressions
@{
    Layout = null;
    var userAgent = Request.Headers[HeaderNames.UserAgent];
    // Using regex we look for some standard User Agents that are bots
    var isNotBotAgent = !Regex.IsMatch(
        userAgent,
        @"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google",
        RegexOptions.IgnoreCase
    );
}

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="~/" />

    <link href="css/site.css" rel="stylesheet" />
    <link href="CodyAnhorn.Tech.styles.css" rel="stylesheet" />
</head>
<body>
    <component type="typeof(App)" render-mode="ServerPrerendered" />

    @if (isNotBotAgent)
    {
        @* We are only including the Blazor Server js when we are not a bot. *@
        @* This make it so the site is just a normal Server Side Render application, that works better with bots and user that are not using JavaScript. *@
        <script src="_framework/blazor.server.js"></script>
    }

</body>
</html>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK