1

I have an application in Angular 4 for file upload and a server in .NET Core 2.

This is my api method:

    [HttpPost]
    [Route("PostFileUploadIFile")]
    public async Task<IActionResult> PostFileUpload(APIDocumentsSettings aPIDocumentsSettings)
    {
        try
        {
            var fileUpload = aPIDocumentsSettings.FileForUpload;
            if (fileUpload.Length < 0 || fileUpload == null)
            {
                return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Incorrect Base64 format" });
            }

            string fileDir = Path.Combine(hostingEnvironment.WebRootPath, aPIDocumentsSettings.DocumentType, aPIDocumentsSettings.Version);
            if (!Directory.Exists(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }
            string file = Path.Combine(fileDir, DateTime.Now.Ticks + ".pdf");
            if (!string.IsNullOrEmpty(fileUpload.FileName))
            {
                byte[] filebytes = Convert.FromBase64String(fileUpload.FileName);
                FileStream fs = new FileStream(file,
                                               FileMode.CreateNew,
                                               FileAccess.Write,
                                               FileShare.None);
                fs.Write(filebytes, 0, filebytes.Length);
                fs.Close();
            }
            using (var fs = new FileStream(Path.Combine(file), FileMode.Create))
            {
                await fileUpload.CopyToAsync(fs);
            }

            if (String.IsNullOrEmpty(file))
            {
                return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "File Upload Failed, Path not found!" });
            }

            return Ok(file.Substring(file.LastIndexOf(aPIDocumentsSettings.DocumentType)));


        }
        catch (Exception ex)
        {
            return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Exception Occurs" + ex.Message });
        }
    }

This is my APIDocumentsSettings Model:

public class APIDocumentsSettings
{
    public IFormFile FileForUpload { get; set; }
    public string Version { get; set; }
    public string DocumentType { get; set; }
}

This is contained in the startup of the web api project:

public class Startup
{
    public Startup(IConfiguration configuration)
    {          
        this.Configuration = configuration;            
    }

    public IConfiguration Configuration { get; }      
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MastersDbContext>(options =>             options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));            
        services.AddMvc();
        //services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
        services.AddAuthentication()
         .AddOAuthValidation(); 
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
        });
        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequiredApplicationManagerRole", policy => policy.RequireRole("ApplicationManager"));
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
            options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
        });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "Masters API",
                Description = "Masters API give access to all Masters table Web APIs",
                TermsOfService = "None"
            });
        });            
    }       
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Masters API");
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(builder =>
            builder.WithOrigins("*")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            );
        app.UseMvc();
        app.UseAuthentication();
        app.UseStaticFiles();

    }
}

This is my angular code:

 
@Injectable()
export class DocumentupdatingService 
{
  apiRoot:string="http://localhost:8080/api/v1/";

constructor(private _http:Http) 
{ }

create(documentupdating:DocumentsUpdating)
{
  return this._http.post(this.apiRoot+'DocumentsSettings',documentupdating)      
}

destroy(documentupdating:DocumentsUpdating)
{
  return this._http.delete(this.apiRoot+documentupdating.id).map(res=>res.json())  
}
update(documentupdating:DocumentsUpdating)
{
  return this._http.put(this.apiRoot+'DocumentsSettings/'+documentupdating.id,documentupdating)   
}
getAllDocuments()
{
  return this._http.get("http://192.168.91.39:8080/api/v1/DocumentsSettings").map(res=>res.json())
}

uploadFile(formdata:FormData)
{
  console.log(formdata.get('FileForUpload'))
  console.log(formdata.get('Version'))
  console.log(formdata.get('DocumentType'))
  let myHeader = new Headers();
  myHeader.append('Content-Type','multipart/form-data');
  let options=new RequestOptions({headers:myHeader});
  return this._http.post(this.apiRoot+'DocumentsSettings/PostFileUploadIFile/',{'FileForUpload':formdata.get('FileForUpload'),'Version':formdata.get('Version').toString,'DocumentType':formdata.get('DocumentType')},options)
}

}

After Uploading file I get following error:

enter image description here

I have uploaded file through PostMan and its working.

Milo
  • 3,365
  • 9
  • 30
  • 44
Sushil Patil
  • 29
  • 1
  • 5
  • Use the https://webpack.github.io/docs/webpack-dev-server.html#proxy of the `webpack dev server` to make use of http-proxy-middleware to optionally proxy requests to a separate, possibly external, backend server. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – Dmitrij Kuba Dec 05 '17 at 13:54

3 Answers3

1

Enable CORS in your Asp.net Core 2 application. Add this code to ConfigureServices method :

 services.AddCors(options =>
    {
       options.AddPolicy("AllowAllOrigins",
    builder =>
    {
        builder.AllowAnyOrigin();
    });
    });

For more details fellow this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/cors

Houssem Romdhani
  • 332
  • 1
  • 11
0

You'are having CORS issues.
PostMan works and your app doesn't because the browser is blocking your request.
This happens because your app is running in a different origin from your backend.
The browser uses preflight request to know if your backend authorize request from your origin. https://developer.mozilla.org/pt-BR/docs/Glossary/Preflight_request

You should configure a proxy in your dev-server: https://webpack.js.org/configuration/dev-server/#devserver-proxy

Giovane
  • 1,421
  • 1
  • 15
  • 25
0

You need to Enable cross-origin requests in your api. so that a request from a different origin can be served in api origin. To read further about CORS and implementation MSDN - Cors

To fix your problem:

Install nuget package Microsoft.AspNet.WebApi.Cors

Modify your Configure method in Startup.cs file with the following lines,

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // global cors policy
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    }

The above will enable any different origin request(Angular in your case) to be served by the API (ASP.Net core api)

Swinkaran
  • 1,207
  • 1
  • 12
  • 19