ASP .NET Core 2 API направляет метод GET, затем метод POST по первому запросу - PullRequest
0 голосов
/ 20 сентября 2018

Я заметил, что после перезапуска моего ASP .NET API и отправки запроса POST API перенаправляет метод запроса GET, а затем мой метод запроса POST.Это происходит только при первом запросе POST после перезапуска API.Каждый запрос POST после этого направляется непосредственно в мой метод POST без обработки метода запроса GET.Ниже приведены методы класса из моего API.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{

    //public class variable 
    private readonly fujimiContext _context;
    //constructor for ValuesController class
    public ValuesController(fujimiContext context)
    {
        _context = context;

    }
    // GET api/values
    // [Authorize(Policy = "RequireReadRole")]
    [HttpGet("bins")]
    public async Task<IActionResult> GetValues()
    {
       var values = await _context.FcbinCnfg.ToListAsync();

        return Ok(values);
    }

    // POST api/values
   // [Authorize(Policy = "RequireEditRole")]
    [HttpPost("sitepost")]
    public async Task<IActionResult> Post([FromBody] FcbinCnfg [] fcbincnfg)
    {
        if (fcbincnfg == null)
        {
            throw new ArgumentNullException(nameof(fcbincnfg));
        }

        string WindUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string AppName = System.AppDomain.CurrentDomain.FriendlyName;


        if (ModelState.IsValid)
        {
            int i = 0;
            foreach (var obj in fcbincnfg){

                _context.Update(fcbincnfg[i]);
                i++;
            }
            await _context.SaveChangesAsync();
            return StatusCode(201);
        }

        return BadRequest("this does not work");
    }

Файл Startup.cs

namespace FcBin.API
 {
 public class Startup
  {
 public Startup(IConfiguration configuration)
    {
        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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        var connection = @"Server=XXXXX\XXXX;Database=XXXXX;Trusted_Connection=True;";
        services.AddDbContext<fujimiContext>(options => options.UseSqlServer(connection));
        services.AddCors();

        services.AddAuthentication(IISDefaults.AuthenticationScheme);

        services.Configure<IISOptions>(options =>
       {
           options.AutomaticAuthentication = true;       
       });

    }

    // 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.UseDeveloperExceptionPage();
        }
        else
        {
            // app.UseHsts();
        }

        app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
        app.UseMvc();
    }
}
}

Угловой маршрут

import { Routes} from '@angular/router';
import { BinConfigComponent } from './BinConfig/BinConfig.component';
import { BinResolver } from './_resolver/bin.resolver';


export const appRoutes: Routes = [
  {path: 'binconfig'
  , component: BinConfigComponent
  , resolve: {binconfig: BinResolver}, runGuardsAndResolvers: 'always'},
  {path: '', redirectTo: 'binconfig', pathMatch: 'full',   runGuardsAndResolvers: 'always'}
];

1 Ответ

0 голосов
/ 24 сентября 2018

Таким образом, проблема не имела никакого отношения к моим маршрутам или API.Проблема была с моей save() функцией в моем Angular front end.Я подошел к функции как к последовательной проблеме, когда на самом деле браузер / клиент подошел к моей функции с точки зрения эффективности.Ниже приведено то, что браузер попытался оптимизировать

save() {
if (this.dirtyFlag) {
this.dbService.dbsave(this.binconfig).subscribe( () => {
}, error => {
  console.log(error);
});
}
if (this.isFoo && this.valid) {
  this.dbService.dbsavebin(this.newbin).subscribe( error => {
    console.log(error);
   });
} else if (!this.valid && this.isFoo) {
  this.toastr.warning('Enter a Bin Id');
}
 this.router.navigate(['/binconfig']);
}

Здесь у меня был преобразователь маршрута, который перезагрузил страницу, которую я вызвал после сохранения.Присвоение маршрута в конце этого сохранения приведет к тому, что браузер попытается оптимизировать методы POST / GET в функции save() и в преобразователе маршрутов.Я решил проблему, используя вместо этого функцию стрелки для выполнения навигации маршрутизатора после успешного сохранения.

save() {
if (this.dirtyFlag) {
this.dbService.dbsave(this.binconfig).subscribe( () => {
}, error => {
  console.log(error);
}, () => {
  this.router.navigate(['/binconfig']);
  this.toastr.success('Changes Saved');
  this.dirtyFlag = false;
});
}
if (this.isFoo && this.valid) {
  this.dbService.dbsavebin(this.newbin).subscribe( () => {
    this.router.navigate(['/binconfig']);
    this.toastr.success('New Bin Added');
    this.isFoo = false;
  }, error => {
    console.log(error);
  });
} else if (!this.valid && this.isFoo) {
  this.toastr.warning('Enter a Bin Id');
}

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...