【问题标题】:Cross domain image file upload issue using CORS - ASP.NET Web API and jQuery使用 CORS - ASP.NET Web API 和 jQuery 的跨域图像文件上传问题
【发布时间】:2016-06-29 16:09:25
【问题描述】:

我需要使用 ASP.NET Web API 和 AJAX 上传跨域图像。我是这种方法的新手。

HTML

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta charset="utf-8" />
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" id="fileUpload" />
        <input type="submit" value="Upload CORS image" id="btnUpload" />
    </form>
    <div id="response"><!-- AJAX Response --></div>
    <script type="text/javascript">
        //55622
        jQuery.support.cors = true;
        function uploadFile() {
            var fa = new FormData();
            fa.append("upload_pass", document.getElementById("fileUpload").files[0]);
            $.ajax({
                type: "POST",
                url: "http://localhost:5000/api/upload/imagefile",
                data: fa,
                contentType: false,
                processData: false,
                //dataType: "jsonp",
                crossDomain: true,
                success: function (data) {
                    // do something here.
                }
            });
        }
        $(document).ready(function () {
            $("#btnUpload").bind("click", function () {
                uploadFile();
            });
        });
    </script>
</body>
</html>

API 控制器方法

using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Mvc;

namespace WebApiz.Controllers
{
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        [EnableCors("AllowAll")]
        [Route("imagefile")]
        [HttpPost("imagefile")]
        public string ImageFile(object data)
        {
            return data.ToString();
        }
    }
}

我有其他控制器方法可以完美地与[EnableCors("AllowAll")] 一起使用,但这个方法给了我以下错误:

HTTP 错误 405.0 - 方法不允许 您正在查找的页面无法显示,因为正在使用无效的方法(HTTP 动词)。

我完全不知道如何解决这个问题!我提到了thisthis。但老实说,我没有理解清楚。如果有人请帮助我解决我做错了什么以及我需要做些什么来完成这对我来说可以挽救生命!

提前致谢。

【问题讨论】:

    标签: asp.net ajax jquery-file-upload cross-domain-policy


    【解决方案1】:

    我尝试了一些东西,最后这对我有用。

    HTML

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <meta charset="utf-8" />
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" id="fileUpload" name="fileUpload" multiple="multiple" />
            <input type="button" value="Upload CORS image" id="btnUpload" />
        </form>
        <div id="response"><!-- AJAX Response --></div>
        <script type="text/javascript">
            jQuery.support.cors = true;
    
            function uploadFiles(url) {
                var data = new FormData();
    
                var files = $("#fileUpload").get(0).files;
    
                // Add the uploaded image content to the form data collection
                if (files.length > 0) {
                    for (var f = 0; f < files.length; f++) {
                        data.append("UploadedImage", files[f]);
                    }
                }
    
                // Make Ajax request with the contentType = false, and procesDate = false
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (response) {
                        $("#response").html(response);
                    }
                });
            }
    
            $(document).ready(function () {
                $("#btnUpload").bind("click", function () {
                    uploadFiles("http://localhost:5000/api/upload/fileupload");
                });
            });
        </script>
    </body>
    </html>

    控制器

    using Microsoft.AspNet.Cors;
    using Microsoft.AspNet.Hosting;
    using Microsoft.AspNet.Http;
    using Microsoft.AspNet.Mvc;
    using Microsoft.Net.Http.Headers;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace ProjectApi.Controllers
    {
        [Route("api/[controller]")]
        public class UploadController : Controller
        {
            private IHostingEnvironment _environment;
            public UploadController(IHostingEnvironment environment)
            {
                _environment = environment;
            }
    
            [EnableCors("AllowAll")]
            [Route("fileupload")]
            [HttpPost("fileupload")]
            public async Task<object> FileUpload()
            {
                var httpRequest = HttpContext.Request;
                var imageUrls = string.Empty;
                var fileName = string.Empty;
    
                if (httpRequest.Form.Files.Count > 0)
                {
                    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
                    for (var f = 0; f < httpRequest.Form.Files.Count; f++)
                    {
                        var postedFile = httpRequest.Form.Files[f];
                        var files = new List<IFormFile>();
                        files.Add(postedFile);
    
                        foreach (var file in files)
                        {
                            fileName = ContentDispositionHeaderValue.Parse(postedFile.ContentDisposition).FileName.Trim('"');
                            var fileExtension = fileName.Substring(fileName.LastIndexOf("."));
                            var randomFileName = System.DateTime.Now.Ticks.ToString();
                            var finalFileName = randomFileName + fileExtension;
    
                            await file.SaveAsAsync(Path.Combine(uploads, finalFileName));
                            imageUrls += "<img src='http://localhost:5000/uploads/" + finalFileName + "' alt='' /><br />";
                        }
                    }
    
                    return imageUrls;
                }
    
                return "No image were uploaded";
            }
        }
    }

    感谢esiprogrammer 为我指路。但是我没有使用任何自定义模型。

    我也参考了这些文章:

    http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/ http://www.mikesdotnetting.com/article/288/asp-net-5-uploading-files-with-asp-net-mvc-6 http://blog.kotowicz.net/2011/05/cross-domain-arbitrary-file-upload.html

    【讨论】:

      【解决方案2】:

      需要设置EnableCors属性的参数

      要允许所有方法,请使用通配符值“*”。以下示例仅允许 GET 和 POST 请求。

      [EnableCors(origins: "http://localhost:5000", headers: "*", methods: "get,post")]
      

      使用 web.config 启用 CORS:

      以下示例允许所有来源的 CORS

      <system.webserver>
          <httpProtocol>
            <customHeaders>
              <add name="Access-Control-Allow-Origin" value="*" />
              <add name="Access-Control-Allow-Methods" value="GET, POST" />
            </customHeaders>
          </httpProtocol>
      </system.webserver>
      

      【讨论】:

      • 感谢您的快速回复。我用了[EnableCors(origins: "http://localhost:5000", headers: "*", methods: "get,post")],但上面写着the best overload for EnableCorsAttribute does not have a parameter named origins。此外,在我的其他控制器方法中,通过 '[EnableCors("AllowAll")]' 启用 CORS 效果很好。我不必在任何地方对其进行参数化。在Startup.cs 我已经以这种方式配置了 Cors:public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ app.UseCors("AllowAll"); } 我还需要在 web.config 中添加条目吗?
      • services.AddCors(options =&gt; options.AddPolicy("AllowAll", p =&gt; p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); 这就是我在 1Startup.cs > ConfigureServices` 方法中设置 Cors 的方式,它告诉系统允许所有来源、所有方法和 AllHeaders。那么为什么我必须在控制器内部的方法级别或web.config level/s 参数化[EnableCors]?事实上,只有[EnableCors("AllowAll")] 的其他方法工作得很好。但是,他们都没有向服务器上传任何内容。
      • 视情况而定,您可能希望为所有方法启用 CORS,以便可以使用 web.config 或在启动时启用它,但如果您只想为某些特定方法启用它,则需要启用它每个控制器/每个带有属性的操作。
      • 但我猜你的问题是由于另一个问题而不是CORS。你试过在localhost中调用这个方法吗?你为什么使用object 作为参数你尝试过使用自定义模型吗?
      • 是的,我只在 localhost 中调用该方法。我的 WebAPI 和使用这些方法的站点位于不同的端口。而且我还没有使用自定义模型。
      猜你喜欢
      • 2017-01-11
      • 2014-01-27
      • 2015-07-02
      • 1970-01-01
      • 2018-05-19
      • 2014-08-15
      • 2021-01-28
      • 1970-01-01
      • 2016-02-27
      相关资源
      最近更新 更多