[英]How to write a post method which accepts JSON in Nancy and how to call it form a C# client?
[英]How to write post method in angular and c#?
嗨,我想編寫一個post
方法,以便我可以在我的數據庫中添加新數據。 我知道如何寫get
但我不知道如何寫 post 這是我的get
in angular 代碼:
constructor(private customerService: CustomerService) {
}
ngOnInit() {
this.customerService.getCustomers()
.subscribe((data) => {
console.log(data);
this.customers = data;
})
}
這是我的后端代碼:
[AllowAnonymous]
public class CustomerController: ControllerBase
{
private readonly ICustomerService _service;
public CustomerController(ICustomerService service)
{
_service = service;
}
[HttpGet]
[AllowAnonymous]
[Route("api/customer/getcustomer")]
public Task<List<CustomerDto>> GetCustomer()
{
return _service.GetCustomer();
}
我怎樣才能用 c# 和 angular 寫post
?
// POST Customer Create A New Customer
[HttpPost("CustomerDto")]
public async Task<ActionResult<CustomerDto >> Post([FromBody] CustomerDto
customer)
{
Customer trueorfalse =await
CustomerServices.GetCustomerByEmail(Customer.Email);
if (trueorfalse!=null)
{
ModelState.AddModelError("email", "Customer email already in use");
return BadRequest(ModelState);
}
try
{
if (Customer== null)
{
_logger.LogError("Customer object sent from client is null.");
return BadRequest("Customer object is null");
}
if (!ModelState.IsValid)
{
_logger.LogError("Invalid Customer object sent from client.");
return BadRequest("Invalid model object");
}
Customer result = await CustomerServices.SaveCustomer(Customer);
Customer e = new Customer();
return CreatedAtAction(nameof(GetCustomer),new { id = result.CustomerId}, result);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside Customer action:
{ex.Message}");
return StatusCode(StatusCodes.Status500InternalServerError,
}
}
你可以這樣做:
[HttpPost]
//only use frombody if you are planning on sending something from your body.
public HttpResponseMessage tmpName([FromBody]MyClass myClass)
{
//write code here
return new HttpResponseMessage((HttpStatusCode)200);
}
你會需要這樣的東西。 但我認為你可以通過一些研究來管理。
C#
[HttpPost]
[Route("api/customer/createCustomer")]
[ProducesResponseType((int)HttpStatusCode.Created)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Example([FromBody]CustomerDto customer)
{
//do smth
return Created();
}
角度:
this.post<ICreateCustomer, ICustomerr>(this.api.url("customer"),
Customer,
errorParams,
(u) => ({
...customer
]
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.