I'm trying to build a new API in ASP.Net Core 2.0 to upload a single file from javascript. I write the asp.net core code and try to test it from Postman, but I receive the message "Could not get any response"
Down, the API class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Caching.Memory;
using System.IO;
using SDN.Portal.Components;
using TinifyAPI;
namespace SDN.Portal.Controllers
{
public class ApiController : BaseController
{
private IHostingEnvironment _env;
public ApiController([FromServices] IOptions<AppSettings> appSettings,
[FromServices] IMemoryCache memoryCache) : base(appSettings, memoryCache)
{
}
[HttpPost("api/upload")]
public async Task<IActionResult> UploadImage(IFormFile image)
{
_env = Startup._env;
var pathProvider = new PathProvider(_env);
var pathImage = $"./images/post/{image.FileName}.{image.ContentType}";
var newPath = pathProvider.MapPath(pathImage);
if (image.Length > 0)
{
using (var fileStream = new FileStream(newPath, FileMode.Create))
{
await image.CopyToAsync(fileStream);
}
}
return Ok(new { status = true, message = "Upload Ok", link = newPath }) ;
}
}
}
and down, the response from Postman Erro from postman
The startup.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Rewrite;
using SDN.Core;
using System.Globalization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http.Extensions;
namespace SDN.Portal
{
public class AppSettings
{
public string SiteUrl { get; set; }
public string CheckoutUrl { get; set; }
public string StorageUrl { get; set; }
public bool Analytics { get; set; }
public string ValidationMessage { get; set; }
public string SucessMessage { get; set; }
public string ErrorMessage { get; set; }
public string MailSender { get; set; }
public string SmtpServer { get; set; }
public string SmtpPort { get; set; }
public string SmtpUserName { get; set; }
public string SmtpUserAPIKey { get; set; }
public string RecaptchaSecret { get; set; }
public string SiteLocale { get; set; }
public int PageSize { get; set; }
public double CacheTime { get; set; }
public string SelectPlanURL { get; set; }
public string AdvertiseURL { get; set; }
public string BaseCentralURL { get; set; }
public string TinifyKey { get; set; }
}
public class Startup
{
internal readonly AppSettings _appSettings;
internal static IHostingEnvironment _env;
public Startup(IHostingEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
//Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
// Make the session cookie essential
//options.Cookie.IsEssential = true;
});
services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
SDN.Core.Common.Configuration.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error/{0}");
var options = new RewriteOptions().AddRedirectToWww().AddRedirectToHttps(StatusCodes.Status301MovedPermanently);
app.UseRewriter(options);
app.UseMvcWithDefaultRoute();
}
var locale = "pt-BR";
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions
{
SupportedCultures = new List<CultureInfo> { new CultureInfo(locale) },
SupportedUICultures = new List<CultureInfo> { new CultureInfo(locale) },
DefaultRequestCulture = new RequestCulture(locale)
};
app.UseSession();
app.UseRequestLocalization(localizationOptions);
app.UseStaticFiles();
app.UseMvc(routes =>
{
//routes.IgnoreRoute("{file}.js");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public class IgnoreRouteMiddleware
{
private readonly RequestDelegate next;
// You can inject a dependency here that gives you access
// to your ignored route configuration.
public IgnoreRouteMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.HasValue && (
context.Request.Path.Value.Contains(".ico")
|| context.Request.Path.Value.Contains(".xml")
|| context.Request.Path.Value.Contains(".png")
|| context.Request.Path.Value.Contains(".txt")
|| context.Request.Path.Value.Contains(".htm")
|| context.Request.Path.Value.Contains(".js")
|| context.Request.Path.Value.Contains(".jpg")
|| context.Request.Path.Value.Contains(".gif")
|| context.Request.Path.Value.Contains(".css")
|| context.Request.Path.Value.Contains(".scss")
|| context.Request.Path.Value.Contains(".json")
))
{
context.Response.StatusCode = 404;
//Console.WriteLine("Ignored!");
return;
}
await next.Invoke(context);
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.