๐Ÿ”ฎ Sanity Create is here. Writing is reinvented. Try now, no developer setup

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?
Dec 20, 2022, 7:24 PM
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?
Dec 20, 2022, 7:31 PM
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.
Dec 20, 2022, 7:49 PM
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?
Dec 20, 2022, 7:51 PM
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.
Dec 20, 2022, 7:54 PM
//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
Dec 20, 2022, 7:59 PM
Thank you so much!! This is exactly what I was looking for.
Dec 20, 2022, 8:01 PM
You're welcome ๐Ÿ˜Š Good luck!
Dec 20, 2022, 8:01 PM
Oh yeah and you need these in Program.cs:
using Sanity.Linq;
using MainAPI.Sanity;
Dec 20, 2022, 8:08 PM
Okay thank you. Will we have to create instances of these?
Dec 20, 2022, 8:10 PM
What do you mean by that? What is these?
Dec 20, 2022, 8:10 PM
Nevermind I understand now. I have to reference them in Program.cs.
Dec 20, 2022, 8:12 PM
They're imports ๐Ÿ‘
Dec 20, 2022, 8:12 PM
right. ๐Ÿ‘
Dec 20, 2022, 8:13 PM

Sanityโ€“ build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?