Skip to content
项目

关于

这是一个可移植库,可在几乎任何 C# 应用程序中调用 WordPress REST API。

网站与应用开发

这些数字如何统计

可以做什么

  • Authentication using JSON Web Tokens (JWT)
  • HttpResponsePreProcessing: manipulate the API response before deserializing it

实测星标增长

24小时
0
7天
0
15天
0
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

WordPressPCL

Integration Tests NuGet

This is a .NET 10 library for consuming the WordPress REST API in C# applications. If you find bugs or have any suggestions, feel free to create an issue.

Documentation

https://wp-net.github.io/WordPressPCL/

Quickstart

WordPress Requirements

Since WordPress 4.7 the REST API has been integrated into the core so there's no need for any plugins to get basic functionality.

If you want to access protected endpoints, there are two authentication options:

  • Authentication using JSON Web Tokens (JWT) (plugin required)
  • Basic Authentication using Application Passwords

Supported JWT Authentication Plugins (install either of the following):

To use Application Passwords for authentication read through:

https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/

Including WordPressPCL

The WordPressPCL API Wrapper is avaiable through NuGet:

> Install-Package WordPressPCL

Release Process

WordPressPCL uses GitHub Releases as the source of truth for publishing new package versions.

  1. Update CHANGELOG.md with the release highlights.
  2. Create a GitHub release with a vX.Y.Z tag (or vX.Y.Z-suffix for pre-releases) and GitHub-generated release notes.
  3. Publishing that release triggers the NuGet workflow, which builds and publishes the same version to NuGet.

Runtime Requirement

WordPressPCL 3.0 targets .NET 10 only. Upgrading from 2.x is a breaking change and requires applications and test environments to move to the .NET 10 SDK/runtime before restoring, building, or running tests.

Versioned Reference Docs

Supported Platforms

WordPressPCL 3.0 targets .NET 10 and is intended for applications running on the current .NET platform:

.NET implementation Version support
.NET 10.0

Quickstart: Using the API Wrapper

// Client construction

//pass the Wordpress REST API base address as string
var client = new WordPressClient("https://demo.wp-api.org/wp-json/");

//or pass the base address as strongly typed Uri
const wpBaseAddress = new Uri("https://demo.wp-api.org/wp-json/");
var client = new WordPressClient(wpBaseAddress);

//or to reuse an HttpClient pass the HttpClient with base address set to api's base address
httpClient.BaseAddress = new Uri("https://demo.wp-api.org/wp-json/")
var client = new WordPressClient(httpClient);

// direct-construction ownership:
// - WordPressClient(Uri) creates and owns its internal HttpClient
// - WordPressClient(HttpClient) reuses an external HttpClient and never disposes it

// Posts
var posts = await client.Posts.GetAllAsync();
var postbyid = await client.Posts.GetByIdAsync(id);
var postsCount = await client.Posts.GetCountAsync();

// Comments
var comments = await client.Comments.GetAllAsync();
var commentbyid = await client.Comments.GetByIdAsync(id);
var commentsbypost = await client.Comments.GetCommentsForPostAsync(postid, true, false);

// Plugins
var plugins = await client.Plugins.GetAllAsync(useAuth:true);
var installedplugin = await client.Plugins.InstallAsync("akismet");
var activateplugin = await client.Plugins.ActivateAsync(installedplugin);
var deactivateplugin = await client.Plugins.DeactivateAsync(installedplugin);
var deleteplugin = await client.Plugins.DeleteAsync(installedplugin);

// Authentication
var client = new WordPressClient(ApiCredentials.WordPressUri);

//Either Bearer Auth using JWT tokens
client.Auth.UseBearerAuth(JWTPlugin.JWTAuthByEnriqueChavez);
await client.Auth.RequestJWTokenAsync("username", "password");
var isValidToken = await client.IsValidJWTokenAsync();
  
//Or Basic Auth using Application Passwords
client.Auth.UseBasicAuth("username", "password");

// now you can send requests that require authentication
var response = client.Posts.DeleteAsync(postId);

Dependency injection and IHttpClientFactory

For ASP.NET Core and worker services, prefer registering WordPressClient through DI so that HttpClient pooling is managed by IHttpClientFactory.

using Microsoft.Extensions.DependencyInjection;
using WordPressPCL;

builder.Services
    .AddWordPressClient(
        (services, httpClient) =>
        {
            httpClient.BaseAddress = new Uri(builder.Configuration["WordPress:BaseUrl"]!);
            httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");
        },
        (services, client) =>
        {
            client.Auth.UseBasicAuth(
                builder.Configuration["WordPress:Username"]!,
                builder.Configuration["WordPress:ApplicationPassword"]!);
        });

You can then request WordPressClient anywhere DI is available:

public sealed class PublishWorker(WordPressClient client)
{
    public Task<IReadOnlyList<Post>> GetPostsAsync()
        => client.Posts.GetAllAsync();
}

Supported REST Methods

Create Read Update Delete
Posts yes yes yes yes
Pages yes yes yes yes
Comments yes yes yes yes
Categories yes yes yes yes
Tags yes yes yes yes
Users yes yes yes yes
Media yes yes yes yes
Post Revisions --- yes --- yes
Page Revisions --- yes --- yes
Post Autosaves yes yes --- ---
Page Autosaves yes yes --- ---
Taxonomies --- yes --- ---
Post Types --- yes --- ---
Post Statuses --- yes --- ---
Settings --- yes yes ---
Plugins yes yes yes yes
Themes --- yes --- ---
Search --- yes --- ---
URL Details --- yes --- ---
Block Types --- yes --- ---
Reusable Blocks yes yes yes yes
Navigation yes yes yes yes

Notes:

  • Post revisions are available through client.Posts.Revisions(postId).
  • Page revisions are available through client.Pages.Revisions(pageId).
  • Post and page autosaves are available through client.Posts.Autosaves(postId) and client.Pages.Autosaves(pageId).
  • Block types, reusable blocks and navigation posts are available through client.BlockTypes, client.Blocks and client.Navigation.
  • Block types require WordPress 5.5 or newer and an authenticated user with permission to edit a REST-enabled post type.
  • Reusable blocks require WordPress 5.0 or newer; core requires authentication and suitable post-editing permissions for reads and writes.
  • Navigation posts require WordPress 5.9 or newer. client.Navigation authenticates reads by default because core maps wp_navigation capabilities to edit_theme_options; the route's availability and permissions can still vary with WordPress version and site customization.
  • Discover /wp-json/ rather than assuming these newer routes exist on older or customized sites.

Endpoint Coverage and Gaps

WordPressPCL currently provides dedicated clients for the most common wp/v2 endpoints:

  • Posts, Pages, Comments, Categories, Tags, Users and Media
  • Taxonomies, Post Types, Post Statuses and Settings
  • Post and page revisions via client.Posts.Revisions(postId) and client.Pages.Revisions(pageId)
  • Post and page autosaves via client.Posts.Autosaves(postId) and client.Pages.Autosaves(pageId)
  • Plugins and Themes
  • Search via client.Search
  • URL details via client.UrlDetails (wp-block-editor/v1/url-details, authentication required)
  • Block types, reusable blocks and navigation posts via client.BlockTypes, client.Blocks and client.Navigation

The standard WordPress REST API reference also includes endpoints that do not yet have first-class wrappers in this library, including:

  • newer block editor endpoints such as block rendering, templates, template parts and global styles
  • navigation fallback, sidebars, widgets and widget types

You can still work with unsupported standard endpoints, plugin namespaces and site-specific custom endpoints by using CustomRequest.

// Discover the namespaces and routes exposed by a site
dynamic apiIndex = await client.CustomRequest.GetAsync<dynamic>("", ignoreDefaultPath: true);

// Call a plugin or custom namespace route
dynamic customEndpoint = await client.CustomRequest.GetAsync<dynamic>("wc/v3/products", useAuth: true);

For a fuller endpoint-by-endpoint summary, see docs/v3/endpoint-coverage.md.

Additional Features

Contribution Guidelines

We're very happy to get input from the community on this project! See CONTRIBUTING.md for full details on setting up a development environment, running tests, and submitting pull requests.

In brief:

  • Open an issue before starting work so we can discuss scope and avoid duplicate effort.
  • Follow the Microsoft C# coding guidelines.
  • Add or update tests to cover your change.
  • In order to run the tests locally, refer to the dev/install.md file and use Docker Compose.

探索相关项目

加载中…