How to integrate Sanity with a .NET middleware

13 replies
Last updated: Dec 20, 2022
I am trying to get Sanity to talk to my middleware (.Net) instead of the front-end (NextJS, React). Is there any documentation on how to do this or can you please direct me to someone who might be able to show me how to get this done?
Hi! I'm working on a project that calls Sanity from .NET. I didn't find a whole lot of documentation for it, but there is some here: https://www.sanity.io/docs/dot-net
Is there anything in particular you are having problems with?
I was able to get Sanity to push content to my front-end. Now I'm trying to get it to do the same thing but through our middleware and wasn't sure how to do it.
When you say you have Sanity pushing content, do you mean that you are querying Sanity or do you have a set up where Sanity somehow knows your frontend and sends updates there?
I 'm sorry. I mean I queried Sanity and my front-end through a client.js file knows about Sanity and I can pull data from it. How do I do that through the middleware is my issue. There examples for React and NextJS are excellent but other then the document you shared I don't see any examples on how to do it.
//sanity
var options = new SanityOptions
{
    ProjectId = builder.Configuration.GetSection("Sanity")["ProjectId"],
    Dataset = builder.Configuration.GetSection("Sanity")["Dataset"],
    Token = builder.Configuration.GetSection("Sanity")["Token"],
    UseCdn = false,
    ApiVersion = "v1"
};

var sanityDataContext = new SanityDataContext(options);
builder.Services.AddSingleton(sanityDataContext);
This is how I set it up. This is from Program.cs. The secrets is kept in appsettings.json in my case. Then I inject SanityDataContext in the constructor of the files where I communicate with sanity in the same way you would with database contexts if you were communicating with those in a repository class
Thank you so much!! This is exactly what I was looking for.
You're welcome 😊 Good luck!
Oh yeah and you need these in Program.cs:
using Sanity.Linq;
using MainAPI.Sanity;
Okay thank you. Will we have to create instances of these?
What do you mean by that? What is these?
Nevermind I understand now. I have to reference them in Program.cs.
They're imports πŸ‘
right. πŸ‘

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?