Ich werde unten erklären, was ich bereits getan habe.
Code: Select all
CustomersController
Code: Select all
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; // Required for configuration
using Microsoft.Store.PartnerCenter; // Required for Partner Center SDK
using Microsoft.Store.PartnerCenter.Models.Customers; // Required for Customer model
using ConnectingToMicrosoftPartnerAPI.Models; // Required for your DTO
using Microsoft.AspNetCore.Authorization;
using Microsoft.Store.PartnerCenter.Extensions;
using Microsoft.Identity.Client;
namespace ConnectingToMicrosoftPartnerAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly ILogger _logger; // Optional but good practice
public CustomersController(IConfiguration configuration, ILogger logger)
{
_configuration = configuration;
_logger = logger;
}
[HttpGet]
public async Task GetCustomers()
{
try
{
// Retrieve configuration values
var tenantId = _configuration["PartnerCenter:TenantId"];
var clientId = _configuration["PartnerCenter:ClientId"];
var clientSecret = _configuration["PartnerCenter:ClientSecret"];
if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
{
_logger.LogError("Partner Center configuration is missing.");
return StatusCode(500, "Server configuration error: Partner Center credentials missing.");
}
// Authenticate with MSAL to get an access token
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
var authResult = await app.AcquireTokenForClient(new[] { "https://api.partnercenter.microsoft.com/.default" }).ExecuteAsync();
// Use the access token to create Partner Center credentials
var partnerCredentials = PartnerCredentials.Instance.GenerateByApplicationCredentials(
clientId,
clientSecret,
tenantId);
var partnerOperations = PartnerService.Instance.CreatePartnerOperations(partnerCredentials);
// Get the customer collection
var customers = await partnerOperations.Customers.GetAsync();
// Process the customer list and map to DTOs
var CustomerListData = customers.Items.Select(customer => new CustomerListData
{
CusName = customer.CompanyProfile?.CompanyName,
CusMicrosoftID = customer.Id,
CusPrimaryDomainName = customer.CompanyProfile?.Domain,
CusRelationship = customer.RelationshipToPartner.ToString(),
CusTags = new List()
}).ToList();
return Ok(CustomerListData);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving customers from Partner Center.");
return StatusCode(500, "An error occurred while retrieving customer data.");
}
}
}
}
Code: Select all
using Microsoft.EntityFrameworkCore;
using ConnectingToMicrosoftPartnerAPI.Models;
namespace ConnectingToMicrosoftPartnerAPI.Data
{
public class APIContext : DbContext
{
public APIContext(DbContextOptions options)
: base(options)
{
}
}
}
Code: Select all
namespace ConnectingToMicrosoftPartnerAPI.Models
{
public class CustomerListData
{
public string? CusName { get; set; }
public string? CusMicrosoftID { get; set; }
public string? CusPrimaryDomainName { get; set; }
public string? CusRelationship { get; set; }
public List? CusTags { get; set; }
}
}
< /code>
Program.cs
Code: Select all
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.Identity.Client;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// --- START: Add Authentication and Authorization Services ---
// Install Microsoft.Identity.Web NuGet package if needed:
// Right-click project -> Manage NuGet Packages -> Browse -> Search for Microsoft.Identity.Web -> Install
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")); // Reads config from the "AzureAd" section
builder.Services.AddAuthorization(); // Add Authorization services
// --- END: Add Authentication and Authorization Services ---
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
/*
app.UseAuthentication(); // Enable authentication middleware
app.UseAuthorization();
*/
// --- END: Add Authentication and Authorization Middleware ---
app.MapControllers();
app.Run();
< /code>
I have hidden the TenantID