将图像/文件上载到服务器时,ServiceStack会抛出UnauthorizedAccessException

时间:2014-09-28 13:09:19

标签: android stream xamarin.android servicestack filestream

我在@scott How do I upload an image to a ServiceStack service?

的答案中使用了以下代码
[Route("/upload","POST")]
public class UploadFileRequest
{
    // Example of other properties you can send with the request
    public string[] Tags { get; set; }
}

class MyFileService : Service
{
    public bool Post(UploadFileRequest request)
    {
        // Check a file has been attached
        if(Request.Files == null || Request.Files.Length == 0)
            throw new HttpError(400, "Bad Request", "No file has been uploaded");

        // Save the file
        Request.Files[0].SaveTo(Request.Files[0].FileName);

        // Maybe store the tags (or any other data in the request)
        // request.Tags

        return true;
    }
}
  

然后在Android应用中使用JsonServiceClient,那么您只需要这样做:

var filename = "cab.jpg"; // The path of the file to upload
var client = new JsonServiceClient("http://212.175.132.168/service/api/");
using(var fileStream = File.OpenRead(filename))
{
    client.PostFileWithRequest<bool>(fileStream, "cab.jpg", new UploadFileRequest { Tags = new[] { "Cab", "Taxis", "NewYork", "Yellow" }});
}

我在我的DTO和我的Android应用中使用了这个,但是当我尝试发送时总是因以下服务器错误而失败:

{"ResponseStatus": {"ErrorCode":"UnauthorizedAccessException","Message":"'C:\\Windows\\SysWOW64\\inetsrv\\a.png' path denied.", 'C:\Windows\SysWOW64\inetsrv\a.png' path denied.

任何人都可以共享Monodroid ServiceStack图片上传示例吗?

感谢。

1 个答案:

答案 0 :(得分:2)

您在Monodroid客户端中使用的示例代码that you have taken from my answer given here没有任何问题。它可以在没有修改的情况下使用ServiceStack PCL库在Monodroid上运行。

MonoDroid的:

无需修改。

var filename = "cab.jpg"; // The path of the file to upload
var client = new JsonServiceClient("http://212.175.132.168/service/api/");
using(var fileStream = File.OpenRead(filename))
{
    client.PostFileWithRequest<bool>(fileStream, "cab.jpg", new UploadFileRequest { Tags = new[] { "Cab", "Taxis", "NewYork", "Yellow" }});
}

服务器文件权限错误:

上传到ServiceStack服务时收到的错误消息表明您的服务器进程无权将文件写入此目录C:\Windows\SysWOW64\inetsrv

{
    "ResponseStatus":     
    {
        "ErrorCode":"UnauthorizedAccessException",
        "Message":"'C:\Windows\SysWOW64\inetsrv\a.png' path denied."
    }
}

您需要更新服务器端服务,以将文件写入服务有权访问的路径。

class MyFileService : Service
{
    public bool Post(UploadFileRequest request)
    {
        // Check a file has been attached
        if(Request.Files == null || Request.Files.Length == 0)
            throw new HttpError(400, "Bad Request", "No file has been uploaded");

        // Replace with a path you have permission to write to
        var path = @"c:\temp\image.png";

        // Save the file
        Request.Files[0].SaveTo(path);

        // Maybe store the tags (or any other data in the request)
        // request.Tags

        return true;
    }
}

如果您修复了权限错误,您会看到它有效。