【问题标题】:ASP .NET Core 2 API routes to GET method then POST method on first requestASP .NET Core 2 API 路由到 GET 方法,然后在第一次请求时 POST 方法
【发布时间】:2019-02-24 04:53:39
【问题描述】:

我注意到,在我重新启动我的 ASP .NET API 并发送一个 POST 请求后,API 路由到 GET 请求方法,然后是我的 POST 请求方法。这只发生在我重新启动 API 后的第一个 POST 请求上。在此之后的每个 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'}
];

【问题讨论】:

  • 您确定您没有遭受浏览器预测网址输入的困扰吗? IE。 chrome 会预测您正在输入的 url,并在您完成输入之前自动获取它。如果你真的想测试它,使用一个rest测试客户端,然后你可以确认不是浏览器在做。
  • 我目前正在使用 firefox 作为我的浏览器,所以我不确定这个问题是否仍然存在。我将如何使用休息测试客户端?
  • install.advancedrestclient.com/#/features 这是我目前最喜欢的休息测试客户端,也可以作为 chrome 扩展使用。调试 api 时,最好使用 rest 测试客户端,而不是浏览器。
  • 但是,如果您遇到身份验证问题,它确实会使事情变得复杂。 IE。我现在正在构建一个 rest api,它使用来自父域的通过 ADFS 身份验证。 Authentication cookie 被传递给 API,以便 api 声明经过身份验证。我无法在休息客户端中对其进行测试,因为我没有那个 cookie。我必须在登录后将cookie标头复制出来并将它们放入其余客户端,大皮塔。
  • 我去看看谢谢。我目前的设置是一个 Angular 2 前端和一个 ASP .NET 后端。当我让我的 Angular 2 应用程序运行然后重新启动 ASP .NET 后端时,我遇到了这个问题。当我添加 Windows 身份验证时,情况会变得更糟。它总是在 POST 路由之前处理 GET 路由。真的很奇怪

标签: c# asp.net-mvc httprequest


【解决方案1】:

所以这个问题与我的路由或 API 无关。问题在于我的 Angular 前端中的 save() 函数。当实际上浏览器/客户端从效率的角度接近我的功能时,我将功能作为一个顺序问题来处理。以下是浏览器尝试优化的内容

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']);
}

在这里,我有一个路由解析器重新加载我在保存后触发的页面。在此保存结束时跟踪路由将导致浏览器尝试优化 save() 函数和路由解析器中的 POST / GET 方法。我解决了这个问题,而是在成功保存后使用箭头功能执行路由器导航。

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-02
    • 2019-04-13
    • 2018-03-13
    • 2021-12-18
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多