我正在尝试创建一个角度函数来调用web api来上传文件。我执行它时遇到错误。以下是功能和错误消息。
$scope.UploadFiles = function (id) {
debugger;
var fd = new FormData($('form')[1]);
var config = {
headers: {
'Content-Type': undefined,
'cache': false,
'processData': false,
},
transformRequest: angular.identity,
data:fd
};
$http.post('/api/Project/PostProjectFiles', id, config)
.then(function (response) {
alert('File Upload SUCCESS'+response.data);
})
.catch(function (response) {
alert('File Upload FAILED: ' + JSON.stringify(response));
console.log(response.data);
})
错误讯息:
"Message":"No HTTP resource was found that matches the request URI 'http://localhost:63104/api/Project/PostProjectFiles'.","MessageDetail":"No action was found on the controller 'Project' that matches the request."
我的API只接受一个参数
public HttpResponseMessage PostProjectFiles(int id)
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0 && id>0)
{
Project objProject = dbContext.Projects.Find(id);
int i = 0;
foreach (string file in httpRequest.Files)
{
if (i == 0)
{
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName.ToString();
if(!String.IsNullOrEmpty(fileName))
{
var fileNameWithID = id.ToString() + "_A_" + fileName;
var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + fileNameWithID);
postedFile.SaveAs(filePath);
objProject.AFileID = fileNameWithID;
objProject.AFile = fileName;
}
}
else if (i == 1)
{
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName.ToString();
if (!String.IsNullOrEmpty(fileName))
{
var fileNameWithID = id.ToString() + "_N_" + fileName;
var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + fileNameWithID);
postedFile.SaveAs(filePath);
objProject.NFileID = fileNameWithID;
objProject.NFile = fileName;
}
}
else if (i == 2)
{
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName.ToString();
if (!String.IsNullOrEmpty(fileName))
{
var fileNameWithID = id.ToString() + "_Other_" + fileName;
var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + fileNameWithID);
postedFile.SaveAs(filePath);
objProject.OtherFileID = fileNameWithID;
objProject.OtherFile = fileName;
}
}
i++;
}
dbContext.SaveChanges();
result = Request.CreateResponse(HttpStatusCode.Created);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
另请注意,操作方法存在于控制器中,我不知道为什么会出现错误。
配置,
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);