我在 asp.net web api 中创建了一个 web api,因为所有方法都可以在本地计算机上完美运行,但是
通过我在 vercel 上托管网站的网站
当我通过此调用 get 方法有效但 post 方法无效时
作为
后端API在我的系统中
当我打电话时
const onCreateCustomer = async (event) => {
event.preventDefault();
//setLoading(true);
setError(null);
const formData = new FormData();
formData.append("name", customer.c_name);
formData.append("email", customer.c_email);
formData.append("password", customer.c_password);
formData.append("phone", customer.phoneno);
formData.append("address", customer.address);
formData.append("disease", customer.disease);
if (lat !== null && lon !== null) {
formData.append("latitude", lat);
formData.append("longitude", lon);
}
try {
const response = await fetch(
`https://www.quettacafe.com/FoodDeliverySystems/api/customer/signup`,
{
method: "POST",
body: formData,
headers: {
Accept: "*/*",
},
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.message || `HTTP error! Status: ${response.status}`
);
}
const data = await response.json();
console.log("Signup response:", data);
const latestCustomer = await fetchLatestCustomer(lat, lon);
navigate("/LoginCustomer");
} catch (error) {
console.error("Signup error:", error);
setError(error.message);
} finally {
setLoading(false);
}
};
我的 Web api 函数是 (c#)
[HttpPost]
public HttpResponseMessage Signup()
{
try
{
var httpRequest = HttpContext.Current.Request;
// Retrieve form data
var name = httpRequest.Form["name"];
var email = httpRequest.Form["email"];
var password = httpRequest.Form["password"];
var phone = httpRequest.Form["phone"];
var address = httpRequest.Form["address"];
var latitude = httpRequest.Form["latitude"];
var longitude = httpRequest.Form["longitude"];
var disease = httpRequest.Form["disease"];
var account = db.customer.Where(s => s.email == email).FirstOrDefault();
if (account != null)
{
return Request.CreateResponse(HttpStatusCode.OK, "Already exists");
}
else
{
customer cus = new customer()
{
name = name,
email = email,
password = password,
phone = phone,
address = address,
disease=disease
};
db.customer.Add(cus);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.Created, cus);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
cors已启用
我添加了启用 cors 的线路
POST https://www.quettacafe.com/FoodDeliverySystems/api/customer/signup 405(不允许的方法)
我的路线配置正确,这是我的route.config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Fooddeliverysystems
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
[EnableCors(origins: "*", headers: "*", methods: "*")]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Fooddeliverysystems
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
我试图让方法发布工作
我尝试添加标题
无论是前端还是后端
我将 url 更改为 http localhost
它在本地主机网站上本地运行
但从我的 www.quettacafe.com 域名无法正常工作
我的其他获取方法工作正常
将 API 响应 从 HttpResponseMessage 更改为 IActionResult 。当从控制器返回值时,请确保返回为 Ok(Request.CreateResponse(HttpStatusCode.Created, cus)); 结果,这就是如何处理成功请求的方式。
访问上下文时,请确保使用 IHttpContextAccessor _http。这是标准,并确保对上下文的访问始终如此。因为这允许更多的控制。但请确保始终在 program.cs 中运行激活。您可以使用这个 builder.Services.AddHttpContextAccessor();.
由于您执行等待,请确保在函数前面使用 async 关键字,因为这会使其等待直到等待行完成才能通过线程。
进行这些更改并告知。谢谢。