【问题标题】:consuming asp.net core web api from asp.net core mvc controller for file upload从 asp.net core mvc 控制器使用 asp.net core web api 进行文件上传
【发布时间】:2022-01-26 14:07:36
【问题描述】:

From swagger screenshot当我尝试从 swagger 或邮递员发布文件时,它工作正常。当我尝试从 mvc web 应用程序调用 api 时,它不起作用。我是 asp.net 核心的新手,没有显示错误,但 api 控制器没有点击这里是 mvc 控制器代码

 public async Task<PostViewModel> AddPost(PostViewModel model)
    {
        TestViewModel testViewModel = new TestViewModel()
        {
            Description = model.Description,
            Files = model.Files[0],
        };

        var formContent = new MultipartFormDataContent();
        formContent.Add(new StringContent(testViewModel.Description), "Description");
        formContent.Add(new StreamContent(testViewModel.Files.OpenReadStream()), "Files", Path.GetFileName(testViewModel.Files.FileName));
        HttpClient hc = new HttpClient();
        hc.BaseAddress = new Uri("baseurl");

        var response = await hc.PostAsync("PostFile", formContent);
        string apiResponse = await response.Content.ReadAsStringAsync();
        return null;
        //...
    }`

我的 api 控制器

 [HttpPost("PostFile", Name = "PostFile")]
    public async Task<IActionResult> PostFile([FromForm] TestViewModel testViewModel)
    {
        Console.Write("Hello");

        return null;
    }

【问题讨论】:

    标签: asp.net-core asp.net-core-webapi


    【解决方案1】:

    我的建议是:

    webapi和mvc不在同一个项目,需要在mvc启动时设置cors:

    public void ConfigureServices(IServiceCollection services)
    
            {
                ......
                services.AddCors(options =>
                {
                    options.AddPolicy("any", builder =>
                    {
                        builder.WithOrigins("https://localhost:44320/WeatherForecast", "https://localhost:44393/WeatherForecast/PostFile")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
                });
            }
    
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    
            {
              
                app.UseCors("cors");
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapHub<ChatHub>("/chatHub");
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
    }
    

    控制器中的代码:

     public IActionResult AddPost(PostViewModel model)
    
            {
                TestViewModel testViewModel = new TestViewModel()
                {
                    Description = model.Description,
                    File = model.File,
                };
                var url = "https://localhost:44320/WeatherForecast";
                HttpClient hc = new HttpClient();
                var formContent = new MultipartFormDataContent();
                formContent.Add(new StringContent(testViewModel.Description), "Description");
                formContent.Add(new StreamContent(testViewModel.File.OpenReadStream()), "File",   Path.GetFileName(testViewModel.File.FileName));
                var response =  hc.PostAsync(url,formContent).Result;
                return Ok();
             }
    

    【讨论】:

    • MVC 和 API 是不同的项目,我也尝试过这种方式但没有得到
    • 我更新了我的答案,希望对你有帮助。
    猜你喜欢
    • 2016-11-14
    • 2020-10-31
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 2021-07-07
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多