从Powershell接收数据时,ASP.NET MVC Action的参数为null

时间:2019-04-10 06:13:29

标签: c# asp.net-mvc powershell

我试图了解Powershell如何将数据发送到服务器,并创建了一个ASP.NET MVC项目以及一个Powershell脚本。

MVC操作如下:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string name, string description, string descr)
{
  return new EmptyResult();
}

和Powershell脚本,该脚本应该上传文件以及一些信息:

Add-Type -AssemblyName "System.Web"
$mainUrl= "http://localhost:27701";
function upload {
    param( 
        [string]$filePath,
        [string]$description,
        [string]$genre
        )

    if(![System.IO.File]::Exists($filePath)) {
        Write-Error "$filePath does not exist";
        return;
    }

    $url = $mainUrl + "/Home/Upload";

    $name = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
    $filename = [System.IO.Path]::GetFileName($filePath);
    $dt = [DateTime]::Now.Ticks.ToString("x", [System.Globalization.NumberFormatInfo]::InvariantInfo);
    $boundary = "---------------------------$dt";

    $fileBytes = [System.IO.File]::ReadAllBytes($filePath);
    $fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);
    $fileContentType = [System.Web.MimeMapping]::GetMimeMapping($filename);
    $newLine = "`r`n";

    $bodyLines = ( 
        "--$boundary",
        "Content-Disposition: form-data; name=`"file`"; filename=`"$filename`"",
        "Content-Type: $fileContentType$newLine",
        $fileEnc,
        "--$boundary",
        "Content-Disposition: form-data; name=`"name`"$newLine",
        $name,
        "--$boundary",
        "Content-Disposition: form-data; name=`"description`"$newLine",
        $genre,
        "--$boundary",
        "Content-Disposition: form-data; name=`"descr`"$newLine",
        $description,
        "--$boundary"
    ) -join $newLine;

    $contentType = "multipart/form-data";

    $params1 = @{
        "name" = $name;
        "description" = $description;
        "descr" = $genre;
        "file" = Get-Item $filePath;
    }

    Invoke-WebRequest -Uri $url -Method Post -Body $params1 -ContentType $contentType;
}

upload -filePath "C:\test.txt" -description "Test" -genre "genre";

我尝试了两种方式:-Body $params1-Body $bodyLines,但仍然收到filenamedescriptiondescr空值。

我仍然不明白为什么会收到空值。我的错误在哪里?

0 个答案:

没有答案