You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.NET Razor页面实现OneDrive文件上传下载方案咨询

通过C# Razor页面实现OneDrive Excel文件上传与下载

一、核心前提说明

微软目前已逐步淘汰基于用户名+密码的直接认证方式(ROPC流),尤其是针对个人OneDrive账号,该方式存在安全风险且多数场景已被限制。因此必须通过Microsoft Graph API结合OAuth 2.0授权码流程来实现,这是官方推荐的唯一可行方案。

二、准备工作

  • 在Azure Active Directory(个人账号可注册Azure免费账号)中注册应用:
    • 选择"个人Microsoft账户"作为支持的账户类型
    • 设置重定向URI为你的Razor页面地址,比如https://localhost:xxxx/signin-oidc
    • 为应用添加权限:Files.ReadWrite、offline_access(用于获取刷新令牌,实现持久访问),个人账号直接授予同意即可
    • 记录应用的Client ID和Client Secret

三、Razor页面实现步骤

1. 安装依赖包

在项目中安装以下NuGet包:

Install-Package Microsoft.Graph
Install-Package Microsoft.Identity.Web

2. 配置认证(appsettings.json)

添加以下配置项:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "consumers",
  "TenantId": "consumers",
  "ClientId": "你的应用Client ID",
  "ClientSecret": "你的应用Client Secret",
  "CallbackPath": "/signin-oidc"
}

3. 配置Program.cs(.NET 6+)

添加认证与Graph服务支持:

var builder = WebApplication.CreateBuilder(args);

// 配置Microsoft Identity Web认证
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration)
    .EnableTokenAcquisitionToCallDownstreamApi(new[] { "Files.ReadWrite" })
    .AddMicrosoftGraph()
    .AddInMemoryTokenCaches();

// 添加Razor页面服务
builder.Services.AddRazorPages();

var app = builder.Build();

// 中间件配置
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

4. 上传Excel文件到OneDrive

创建Upload.cshtml.cs后台逻辑:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using System.Threading.Tasks;

[Authorize]
public class UploadModel : PageModel
{
    private readonly GraphServiceClient _graphServiceClient;

    public UploadModel(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }

    [BindProperty]
    public IFormFile ExcelFile { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        if (ExcelFile == null || ExcelFile.Length == 0)
        {
            ModelState.AddModelError("", "请选择要上传的Excel文件");
            return Page();
        }

        using var stream = ExcelFile.OpenReadStream();
        var uploadedFile = await _graphServiceClient.Me.Drive.Root
            .ItemWithPath(ExcelFile.FileName)
            .Content
            .PutAsync<DriveItem>(stream);

        ViewData["Message"] = $"文件上传成功!文件ID: {uploadedFile.Id}";
        return Page();
    }
}

对应的Upload.cshtml页面:

@page
@model UploadModel
@{
    ViewData["Title"] = "上传Excel到OneDrive";
}

<h1>上传Excel文件</h1>

@if (!string.IsNullOrEmpty(ViewData["Message"] as string))
{
    <div class="alert alert-success">@ViewData["Message"]</div>
}

<form method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label>选择Excel文件</label>
        <input type="file" asp-for="ExcelFile" accept=".xls,.xlsx" class="form-control" />
        <span asp-validation-for="ExcelFile" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">上传</button>
</form>

5. 从OneDrive下载Excel文件

创建Download.cshtml.cs后台逻辑:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using System.Threading.Tasks;

[Authorize]
public class DownloadModel : PageModel
{
    private readonly GraphServiceClient _graphServiceClient;

    public DownloadModel(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }

    public async Task<IActionResult> OnGetAsync(string fileName)
    {
        if (string.IsNullOrEmpty(fileName))
        {
            return BadRequest("请指定要下载的文件名");
        }

        var stream = await _graphServiceClient.Me.Drive.Root
            .ItemWithPath(fileName)
            .Content
            .Request()
            .GetAsync();

        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
    }
}

对应的Download.cshtml页面:

@page
@model DownloadModel
@{
    ViewData["Title"] = "从OneDrive下载Excel";
}

<h1>下载Excel文件</h1>

<form method="get">
    <div class="form-group">
        <label>文件名(需包含.xlsx/.xls)</label>
        <input type="text" name="fileName" class="form-control" placeholder="比如test.xlsx" />
    </div>
    <button type="submit" class="btn btn-primary">下载</button>
</form>

四、关键注意事项

  • 授权码流程无需直接处理用户名密码,由微软登录页面完成认证,安全性更高
  • offline_access权限可让应用在用户离线时通过刷新令牌获取新的访问令牌,避免频繁登录
  • 本地开发需使用HTTPS地址,OAuth 2.0授权码流程要求重定向URI为HTTPS

内容的提问来源于stack exchange,提问作者user2409235

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:02:41