我正在尝试使用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'."
}
这不是一个骗局 - 无法找到另一篇解决这一特定组合的文章。
答案 0 :(得分:2)
正如您所料,这是一个路由问题。评论已经确定您与路线和路线前缀属性存在冲突,导致以下路线
api/resize/api/resize/preserveAspectRatio
映射到您的操作。
要获得所需的路线,您可以从控制器本身中删除前缀。
//removed prefix
public class ResizeController : ApiController {
//Matches POST api/resize/preserveAspectRatio
[HttpPost, Route("api/resize/preserveAspectRatio")]
public async Task<IHttpActionResult> resizePreserveAspectRatio() {
//...removed for brevity
}
}
或者从方法
上的路线中删除它[RoutePrefix("api/resize")]
public class ResizeController : ApiController {
//Matches POST api/resize/preserveAspectRatio
[HttpPost, Route("preserveAspectRatio")]
public async Task<IHttpActionResult> resizePreserveAspectRatio() {
//...removed for brevity
}
}
或者在方法属性
上使用波浪号(~
)覆盖路由前缀
[RoutePrefix("api/resize")]
public class ResizeController : ApiController {
//Matches POST api/resize/preserveAspectRatio
[HttpPost, Route("~/api/resize/preserveAspectRatio")]
public async Task<IHttpActionResult> resizePreserveAspectRatio() {
//...removed for brevity
}
}