Declaration of VAR

and some other stuff

OpenSearch in your .NET Core MVC project

2017-08-28 16:30:21 +0200

2017-08-28 16:30:21 +0200 | Comments

OpenSearch is a way to add/integrate your website’s search engine to web-browsers. And here’s how to do such a thing with your .NET Core MVC project website.

At first I wrote this article with .NET Core MVC in mind, but having finished the article, I discovered that there is almost nothing .NET Core MVC specific here, so that’s pretty much a general article that is applicable to any web-framework.

I assume you already have a controller (or some equivalent) with Search action implemented (and it can perform an actual search on your website). You can look at mine here.

And now for OpenSearch.

Essentially, you only need to add a specially formed XML file (OpenSearch description document) to the root level of your website and make it publicly available.

Here’s my opensearch.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  <ShortName>protvshows</ShortName>
  <Description>proTVshows: Most subjective ratings for TV shows</Description>
  <Contact>some@example.org</Contact>
  <Tags>tv tvshows ratings тв сериалы обзоры</Tags>
  <InputEncoding>UTF-8</InputEncoding>
  <Image width="16" height="16" type="image/x-icon">/favicon.ico</Image>
  <Url type="text/html" method="get" template="http://protvshows.com/Search?q={searchTerms}"></Url>
</OpenSearchDescription>

The core thing here is this string:

<Url type="text/html" method="get" template="http://protvshows.com/Search?q={searchTerms}"></Url>

If specifies the search request to your website’s search engine (your Search action).

To make this file publicly available in .NET Core MVC project just put it into the wwwroot directory so it’d be among other static files (you have static files enabled, don’t you). Having done that you should be able to access it from your web-browser like I do: http://protvshows.com/opensearch.xml

And here’s the main reason why at first this article was .NET Core MVC specific - I used to serve opensearch.xml via dedicated controller’s action using custom route, which was stupid and unnecessary as this file can be just placed into wwwroot directory.

One more thing to do - add this tag to your main/public layout/head:

<link rel="search" type="application/opensearchdescription+xml" title="protvshows" href="/opensearch.xml">

Web-browsers pay attention to this tag and add new search engines from discovered OpenSearch description documents. So now your users will be able to look for stuff using your website’s search engine.

For example, here’s what will appear in Safari preferences (Quick Website Search):

And that’s how it works - when you prepend your search query with the website name, Safari offers you to perform the search using this website’s search engine:

And the same thing in Chrome: