0

From swagger screenshotwhen I am trying to post files from swagger or postman it is working fine. When i am trying to call api from mvc web app it is not working.I am new to asp.net core,there is no error showing but the api controller is not hitting here is the mvc controller code

 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;
        //...
    }`

my api controller

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

        return null;
    }

1 Answer 1

0

My suggestion is that:

the webapi isn't in the same project with mvc,You need to set cors in mvc startup:

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?}");
            });
}

Codes in controller:

 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();
         }

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

the MVC and API is a different project, I tried this way also but not getting
I updated my answer, hope it helps you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.