【发布时间】:2018-01-01 23:20:33
【问题描述】:
我正在尝试使用 Web API 做一个简单的文件上传 API。
这里是控制器:
[RoutePrefix("api/resize")]
public class ResizeController : ApiController
{
[HttpPost, Route("api/resize/preserveAspectRatio")]
public async Task<IHttpActionResult> resizePreserveAspectRatio()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
int maxWidth = 100;
int maxHeight = 100;
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
//Do whatever you want with filename and its binaray data.
}
return Ok();
}
}
这是我的 WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
当我使用 PostMan 发布文件时,出现以下错误:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:26303/api/resize/preserveAspectRatio'.",
"MessageDetail": "No type was found that matches the controller named 'resize'."
}
这不是骗人的 - 找不到其他文章来解决这个特定的组合。
【问题讨论】:
-
您的路由前缀已经显示“api/resize/”,那么在您的控制器路由中,您无需再次提及它。只需保持“preserveAspectRatio”
-
作为@PM。提到,您当前的路线是
api/resize/api/resize/preserveAspectRatio -
谢谢 - 嗯,我刚刚将它更改为
preserveAspectRatio用于路由,api/resize用于前缀路由,它仍然给出相同的错误。有什么想法吗? @PM @zaitsman
标签: c# asp.net asp.net-web-api asp.net-web-api2