Почему я получаю 400 и 404 ошибки для моего WebAPI? - PullRequest
1 голос
/ 10 января 2020

Я разрабатываю одно приложение, используя Angular 8 и ASP. Net Core3.1.

enter image description here

Когда я звоню все API немного работают нормально, немногие дают ошибку 400, а некоторые из них ошибку 404.

API дает ошибку 400:

ДЕТАЛИ МОДЕЛИ

public class ServiceOffer
{
   public int Id { get; set; }
   public string ServiceName { get; set; }
   public string ServiceDescription { get; set; }
   public int ServicePrice { get; set; }
   public bool Status { get; set; }
} 

ПОДРОБНОСТИ API

[Produces("application/json")]
[ApiController]
public class ServiceofferController : ControllerBase
{
    [HttpGet]
    [Route("api/v1/serviceoffer/allservice")]
    public async Task<IActionResult> Index()
    {
        var objService = new ServiceBL();
        var mob = await objService.GetAllServices();
        return Ok(mob);
    }

    [Route("api/v1/serviceoffer/addservices")]
    public async Task<IActionResult> AddServices([FromBody] ServiceOffer objSer)
    {
        var objService = new ServiceBL();
        int flag = await objService.AddServiceOffer(objSer);
        return Ok(flag);
    }       

    [HttpPut]
    [Route("api/v1/serviceoffer/update")]
    public static async Task<int> UpdateUser([FromBody] ServiceOffer objSer)
    {
        var objService = new ServiceBL();
        return await objService.UpdateServiceOffer(objSer);
    }
}

API Работает нормально: api / v1 / serviceoffer / allservice

API, выдающий ошибку 400: api / v1 / serviceoffer / addservices

API Giving 404 error: api / v1 / serviceoffer / update

ANGULAR SERVICE

getAllServices(url: string): Observable<IServiceOffer[]> {
return this.http
  .get<IServiceOffer[]>(url)
  .pipe(catchError(this.handleError));
}
getServiceById(url: string, id: number): Observable<IServiceOffer> {
const editUrl = `${url}/${id}`;
// console.log(editUrl);
return this.http
  .get<IServiceOffer>(editUrl)
  .pipe(catchError(this.handleError));
}
 // insert new contact details
 saveService(url: string, cust: IServiceOffer): Observable<any> {
  var Customer = JSON.stringify(cust);
  console.log(url);
  return this.http
  .post(url, Customer, httpOptions)
  .pipe(catchError(this.handleError));
 }
// update contact details
 updateService(url: string, customer: IServiceOffer): Observable<any> {
 //const newurl = `${url}/${id}`;
  return this.http
    .put(url, customer, httpOptions)
    .pipe(catchError(this.handleError));
 }

CONFIG DETAILS

 public class Startup
{
    public IConfiguration Configuration { get; }
    public static string ConnectionString { get; private set; }
    public static Dictionary<string, string> MailSettings { get; private set; }
    public Dictionary<string, string> SmsSettings { get; set; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        ConnectionString = Configuration.GetSection("ConnectionString").GetSection("SalesContext").Value;

        //MailSettings = Configuration.GetSection("SMTP").GetChildren()
        //              .Select(item => new KeyValuePair<string, string>(item.Key, item.Value))
        //              .ToDictionary(x => x.Key, x => x.Value);

        MailSettings = Configuration.GetSection("SMTP").GetChildren().ToDictionary(x => x.Key, x => x.Value);

        services.AddControllersWithViews();
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        //services.AddMvc()
        //     .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        //     .ConfigureApiBehaviorOptions(options =>
        //       {
        //         options.SuppressConsumesConstraintForFormFileParameters = true;
        //         options.SuppressInferBindingSourcesForParameters = true;
        //         options.SuppressModelStateInvalidFilter = true;
        //         options.SuppressMapClientErrors = true;
        //         options.ClientErrorMapping[404].Link = "https://httpstatuses.com/404";
        //     });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {              

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
}

Любой может объясните мне, почему я получаю эту ужасную ошибку?

Заранее спасибо.

Ответы [ 2 ]

1 голос
/ 13 января 2020

Для ошибочного запроса 400 убедитесь, что установлены заголовки 'Content-Type': 'application/json' и правильные данные Customer Json. Я попробовал ваши тестовые данные, и он работает (лучше добавить [HttpPost] в действии).

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

const cust = { id: 1, serviceName: "Test", serviceDescription: "Test", servicePrice: "1000", status: true } 

var Customer = JSON.stringify(cust);

this.http
  .post("/api/v1/serviceoffer/addservices", Customer, httpOptions)
  .subscribe(result => {
    alert(result);
  }, error => console.error(error));

Для 404 Not Found необходимо удалить static на PUT action.

См. Может ли MVC метод действия быть stati c или метод расширения?

Обновление 1/14/2020

Попробуйте использовать servicePrice: 1000 вместо servicePrice: "1000".

Если вы не хотите вносить вышеуказанные изменения. Для asp. net core 3.1 используется System.Text.Json для сериализации и десериализации.

Для использования старого поведения вы можете использовать Json. NET в ASP. NET Core 3.1 проекте, ссылаясь на поддержку J son. NET .

1) Install-Package Microsoft.AspNetCore. Mvc .Newtonsoft Json -Version 3.1.0

2) Добавить services.AddControllersWithViews().AddNewtonsoftJson(); в файле startup.cs

0 голосов
/ 14 января 2020

Эта проблема была с. Net Core 3.0. Встроенный форматер JSON не может преобразовать из Angular цифра c в System.Int32. Прочитав много статей, я узнал, что это ошибка. Решением является установка Microsoft.AspNetCore. Mvc .Newtonsoft Json пакета. И добавьте эту строку Startup.cs services.AddControllers (). AddNewtonsoft Json ();

Это решило мою проблему, теперь все мои службы работают нормально. Спасибо всем вам.

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