如何使用API中的变量访问我的API



我是Blazor的新手,我有一个关于Blazor和API的问题。

在我的.razor文件中,我有这样的代码,我可以在其中获得要填写在表中的数据(因此此代码有效(:

@code {
public PrgUser[] users { get; set; }
IList<PrgUser> selectedUser;
protected override async Task OnInitializedAsync()
{
users = await Http.GetFromJsonAsync<PrgUser[]>("http://localhost:30958/api/Test");
selectedUser = users.Take(1).ToList();
}
}

此代码与API端的以下代码配合得很好:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IneosAppDevContext _context;
public TestController(IneosAppDevContext context)
{
_context = context;
}
// GET: api/Areas
[HttpGet]
public async Task<ActionResult<IEnumerable<PrgUser>>> GetUser()
{
return await _context.PrgUser.ToListAsync();
}
}

但现在我想添加一个DELETE函数,但我不知道如何做到这一点。我有这个代码,但它不能以这种方式工作。。。

.razor文件:

@code {
public PrgUser[] users { get; set; }
IList<PrgUser> selectedUser;
protected override async Task OnInitializedAsync()
{
users = await Http.GetFromJsonAsync<PrgUser[]>("http://localhost:30958/api/Test");
selectedUser = users.Take(1).ToList();
}

protected async Task Enter()
{
Console.WriteLine("Pressed");
var response = await Http.DeleteAsync("http://localhost:30958/api/Test/" + selectedUser[0].UserId);
}
}

API侧:

[HttpDelete]
[Route("/api/Test/{id}")]
public async Task<HttpResponseMessage> Delete(int id)
{
var user = await _context.PrgUser.FindAsync(id);
if (user == null)
{
// if ID not found
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
try 
{
// Success
_context.PrgUser.Remove(user);
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception ex)
{
// Exception
return new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
}

假设API控制器方法被命中。

控制器功能的签名应该如下所示:

[HttpDelete]
[Route("/api/Test/{id}")]
public async Task<HttpResponseMessage> Delete(int id)
{
// if ID not found     
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Id " + id.ToString() + "not found");

// Success
return Request.CreateResponse(HttpStatusCode.OK);  
// Exception
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, Ex);  
}

并且在呼叫中

var response = await Http.DeleteAsync("http://localhost:30958/api/Test/" + selectedUser[0].UserId);
// Check the response and act accordingly

相关内容

  • 没有找到相关文章

最新更新