在Visual Studio解决方案中,我有一个webforms和一个web api项目。我想从webforms项目的html页面发布到web api。以下是我的代码:
Code posting data to web api:
function SaveImage(dataURL) {
dataURL = dataURL.replace('data:image/png;base64,', '');
var data = JSON.stringify(
{
id: 123,
value: dataURL
});
$.ajax({
type: "POST",
url: "http://localhost:65219/saveimage",
contentType: false,
processData: false,
data: data,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Done!");
},
error: onWebServiceFailed
});
}
The web api controller:
[EnableCors(origins: "http://localhost:54270/", headers: "*", methods: "*")]
public class ImageController : ApiController
{
[Route("saveimage")]
[HttpPost]
public HttpResponseMessage SaveImage([FromBody]ImageBinary imageBinary)
{
try
{
//Code to save image
}
catch (Exception ex)
{
//Handle exceptions
}
finally
{
//Cleanup code
}
}
//webapiconfig code:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
//Model class which will be sent to the web api
public class ImageBinary : IImageBinary
{
public int Id { get; set; }
public byte[] Content { get; set; }
}
问题是永远无法访问网络API代码。当我在Chrome中查看开发者工具时,我看到以下错误:
XMLHttpRequest无法加载http://localhost:65219/saveimage。预检的响应具有无效的HTTP状态代码404