如何创建 Web Api 方法的路径

How to make a path to a Web Api method

我想写一个方法,可以动态发送一个文件夹路径,然后发送一个图片文件给客户端。

The code is static

[Route("GetImageFile/{id}")]
[HttpGet]
public HttpResponseMessage GetImageFile(string id)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    FileStream stream = new FileStream(@"d:\gate\images\" + @"\" + id + ".jpg", 
                 System.IO.FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = 
                 new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
    return response;
}

现在我想从客户端动态获取剧集@ "d: \ gate \ images \"

我认为从 uri 中获取第二个操作参数将解决您的问题,但是这种方法并不完全 restful。示例:

[Route("GetImageFile/{id}")]
[HttpGet]
public HttpResponseMessage GetImageFile([FromUri] string id, [FromUri] string searchIn = @"d:\gate\images\") //d:\gate\images\ as default path
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    FileStream stream = new FileStream(searchIn + @"\" + id + ".jpg", 
                 System.IO.FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = 
                 new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
    return response;
}

你可以这样称呼它:

Get GetImageFile/myfileId?searchIn=c:\pub //P.S. Don't forget about URL encoding and security