Удалить событие, а не вызов из углов, где, как получить вызовы метода - PullRequest
0 голосов
/ 13 февраля 2019

Я создал веб-API для стран и пытаюсь получить к нему доступ с угла 7, детали GET и запись GET по идентификатору работают нормально, где метод DELETE не работает.

Когда я пытаюсь получить доступ к DELETE, нет вызова, отправляемого в веб-API с угловой 7.

// DELETE: api/Country/5
[HttpDelete("{id}")]
public IActionResult Delete(long id) {
 Country country = _dataRepository.Get(id);
 if (country == null) {
  return NotFound("The Employee record couldn't be found.");
 }

 _dataRepository.Delete(country);
 return NoContent();
}

// GET: api/Countries
[HttpGet]
public IActionResult Get() {
 IEnumerable < Country > country = _dataRepository.GetAll();
 return Ok(country);
}

// GET: api/Country/5
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(long id) {
 Country country = _dataRepository.Get(id);

 if (country == null) {
  return NotFound("The Employee record couldn't be found.");
 }

 return Ok(country);
}


export class CountriesComponent {

  public countries: Country[];

  bUrl = 'https://localhost:44324/';

  constructor(private http: HttpClient, private router: Router) {

    this.http.get<Country[]>(this.bUrl + 'api/country').subscribe(result => {
      this.countries = result;
    }, error => console.error(error));

  }

  btnClick = function (id) {
    this.router.navigateByUrl('/country-edit/' + id);
  };

  btnDelete = function (id) {
    return this.http.delete(this.bUrl + 'api/Country/' + id);
    //  return this.http.get<Country[]>(this.bUrl + 'api/country/'+     id).subscribe(result => {
    //   this.countries = result;
    // }, error => console.error(error));
  }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddDbContext<DataBaseContext>(opts => opts.UseSqlServer("server=.; database=FoodFactory; Integrated Security=SSPI"));
    services.AddScoped<IDataRepository<Country>, CountryManager>();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(x => x.AllowAnyMethod());
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSpaStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";
        if (env.IsDevelopment())
        {
            spa.UseAngularCliServer(npmScript: "start");
        }
    });
}

1 Ответ

0 голосов
/ 13 февраля 2019

Попробуйте проверить веб-интерфейс веб-API, возможно, отсутствует глагол DELETE.

Попробуйте добавить глагол DELETE, например, как показано ниже:

add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Надеюсь, это поможет.


Обновлено (для .NET Core)

Шаг 1. Регистрация служб CORS

Вызов AddCors в Startup.ConfigureServices для добавления служб CORS в контейнер служб приложения:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

Шаг 2. Включение CORS с помощью промежуточного программного обеспечения CORS

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(x => x
       .AllowAnyOrigin()
       .AllowAnyMethod()
       .AllowAnyHeader()
       .AllowCredentials()
    );
}

Попробуйте, если это работает для вас.

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