簡體   English   中英

為什么我的 WebAPI 出現 400 和 404 錯誤?

[英]Why I am getting 400 and 404 error for my WebAPI?

我正在使用 Angular 8 和 ASP.Net Core3.1 開發一個應用程序。

在此處輸入圖片說明

當我調用所有 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 給出 ​​404 錯誤:api/v1/serviceoffer/update

角度服務

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

配置細節

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

任何人都可以解釋我為什么會收到這個可怕的錯誤?

提前致謝。

對於 400 Bad Request,請確保設置'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,您需要刪除PUT操作上的static

請參閱MVC 操作方法可以是靜態方法還是擴展方法?

2020/1/14 更新

嘗試使用servicePrice: 1000而不是servicePrice: "1000"

如果你不想做以上更改。對於asp.net core 3.1,它使用System.Text.Json進行序列化和反序列化。

為了使用舊行為,您可以通過引用Json.NET support在 ASP.NET Core 3.1 項目中使用 Json.NET。

1) 安裝包 Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.0

2) 添加services.AddControllersWithViews().AddNewtonsoftJson(); 在啟動.cs

此問題與 .Net Core 3.0 相關。 內置 JSON 格式化程序無法從 Angular 數字轉換為 System.Int32。 看了很多文章后,我才知道這是一個錯誤。 解決方案是安裝Microsoft.AspNetCore.Mvc.NewtonsoftJson包。 並添加這一行 Startup.cs services.AddControllers().AddNewtonsoftJson();

它已經解決了我的問題,現在我的所有服務都運行良好。 謝謝大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM