如何从ASP发出PUT请求.asp.net core mvc到Web API在asp.net core?



我需要通过数据库中的API调用保存我在模型中所做的更改。当我在Web上单独运行它时,我检查了我的API是否正常工作。但是它给了我一个错误StatusCode: 405, ReasonPhrase: 'Method Not Allowed'。我试图发送和反对,并试图看看是否已完成的请求。当我试图调试它时,它没有在我的API控制器上发送命中。

这是我的模型类:
public class Customer
{
[Required]
public Guid CustomerId { get; set; }
public int Age { get; set; }
public int Phone { get; set; }
}

PUT方法在API:

[HttpPut]
[Route("api/[controller]/{customer}")]
public IActionResult EditCustomer(Customer customer)
{
var cust = _customerData.EditCustomer(customer);
if (cust == string.Empty)
{
return Ok();
}
else
{
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}

我在项目中使用的方法调用API:

using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiBaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
);
var sum = await client.PutAsJsonAsync("api/Customer/", customer);
if (sum.StatusCode == System.Net.HttpStatusCode.OK)
{

return RedirectToActionPermanent(actionName: "SingIn");
}
else
{
TempData["msg"] = "There is an error";
return View();
}

where baseaddress= {https://localhost:44398/}


EditCustomer方法
public string EditCustomer(Customer customer)
{
try
{
var pro = _customerContext.Customer.Where(e => e.CustomerId == customer.CustomerId).FirstOrDefault();
pro.Age = customer.Age;
pro.Phone = customer.Phone;
pro.Name = customer.Name;
_customerContext.Entry(pro).State = EntityState.Modified;
_customerContext.SaveChanges();
}
catch(Exception e)
{
return e.Message;
}
return string.Empty;
}

您需要通过删除{Customer}来修复您的操作路由,因为您在请求正文中发送Customer,而不是作为路由值

[Route("~/api/Customer")]

请求和

var sum = await client.PutAsJsonAsync("/api/Customer", customer);

或者最好将动作路由名称修改为有意义的

[Route("~/api/EditCustomer")]

var sum = await client.PutAsJsonAsync("/api/EditCustomer", customer);

AsJsonAsync有时会导致问题

试试这个代码

var json = JsonSerializer.Serialize(customer);
//or if you are using Newtonsoft
var json = JsonConvert.SerializeObject(customer);
var contentData = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync("/api/Customer", contentData);

if (response.IsSuccessStatusCode)
return RedirectToActionPermanent("SingIn");
else
{
TempData["msg"] = "There is an error";
return View();
}

但是我更喜欢用

client.PostAsync("/api/EditCustomer", contentData); 

代替Put.

和添加[FromBody]到动作

[HttpPost("~/api/EditCustomer")]
public IActionResult EditCustomer([FromBody] Customer customer)

我不是web API的专业人士,但我怀疑这可能是由于API期望customer在请求URL中。

尝试将API路由更改为[Route("api/[controller]")]

这可能是一个评论,但我没有足够的声誉:)

相关内容

  • 没有找到相关文章

最新更新