Web API put,删除,通过URI发布方法

发布于 2025-01-25 07:29:56 字数 612 浏览 5 评论 0 原文

我对API的整个群体非常陌生。到目前为止,我设法构建了一个已获得,发布,放置和删除方法的Web API。

现在,从ASP.NET项目中,我尝试最终使用我的Web API。

这是我为获得方法所做的:

string info = new WebClient() { }.DownloadString("https://mywebapisite.com/item/" + id);
Item item = JsonConvert.DeserializeObject<Item>(info);

这一切都很好。如您所见,所有GET方法的需求都是ID。

但是,对于帖子方法,我不知道该怎么办。 我可以创建一个新的 item 实例,但不知道该如何处理。

顺便说一句,我还使用asp.net制作我的web.api。 ASP.NET 5中有一个内置功能,称为Swagger。它可以非常成功地执行所有任务。是否有代码的代码。

ps:我知道这个问题必须非常普遍和基本。如果您可以在Stackoverflow中推荐我的另一个问题,或者只是告诉我在Google上搜索什么,我将不胜感激。 (您可能猜到,我什至不知道要搜索什么)

I am very new to the whole consept of API's. So far, I managed to build a web api that has GET,POST,PUT and DELETE methods.

Now, from an ASP.NET project, I try to finally use my web api.

Here's what I do for GET method:

string info = new WebClient() { }.DownloadString("https://mywebapisite.com/item/" + id);
Item item = JsonConvert.DeserializeObject<Item>(info);

This functions all fine. As you can see, all the GET method needs is an id.

However, for the POST method, I have no clue what to do.
I can create a new Item instance, but don't know what to do with it.

By the way, I also used ASP.NET to make my web.api.
There is a built-in feature in ASP.NET 5 called Swagger. It can perform all the tasks very succesfully. Is there like a code-behind for what Swagger does.

PS: I know that this question must be very common and basic. If you could refer me to another question in stackoverflow or simply tell me what to search on google I would appreciate it. (As you may guess, I don't even know what to search for)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

弃爱 2025-02-01 07:29:56

伪代码在C#中消耗发布请求

var requestObj = GetDummyDataTable();

using (var client = new HttpClient())  
{  
    // Setting Base address.  
    client.BaseAddress = new Uri("https://localhost:8080/");  
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
    HttpResponseMessage response = new HttpResponseMessage();  

   // HTTP POST  
   response = await client.PostAsJsonAsync("api/product", requestObj).ConfigureAwait(false);  
    
   if (response.IsSuccessStatusCode)  
   {  
      // Reading Response.  
      string result = response.Content.ReadAsStringAsync().Result;  
      var responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
   }  
}  

pseudo code to consume post request in C#

var requestObj = GetDummyDataTable();

using (var client = new HttpClient())  
{  
    // Setting Base address.  
    client.BaseAddress = new Uri("https://localhost:8080/");  
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
    HttpResponseMessage response = new HttpResponseMessage();  

   // HTTP POST  
   response = await client.PostAsJsonAsync("api/product", requestObj).ConfigureAwait(false);  
    
   if (response.IsSuccessStatusCode)  
   {  
      // Reading Response.  
      string result = response.Content.ReadAsStringAsync().Result;  
      var responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
   }  
}  
冷…雨湿花 2025-02-01 07:29:56

引用以下代码来调用API

////using System.Net.Http.Headers;
////using System.Text;
using (var client = new HttpClient())
{
    var requesturi = "https://localhost:7110/api/ToDo/relativeAddress";

    var item = new TestUserViewModel()
    {
        Name = "John Doe",
        Age = 33
    };
    ////using System.Text.Json;  // use JsonSerializer.Serialize method to convert the object to Json string. 
    StringContent content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");

    //HTTP POST
    var postTask = client.PostAsync(requesturi, content);
    postTask.Wait();

    var result = postTask.Result;
    if (result.IsSuccessStatusCode)
    {
        var Content = await postTask.Result.Content.ReadAsStringAsync();

        return RedirectToAction("Privacy");
    }
}

您可以使用httpclient:这样的API方法

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{ 
    [HttpPost]
    [Route("relativeAddress")]
    public string GetAddress([FromBody] TestUserViewModel testUser)
    {
        return "Address A";
    }

:和这样的结果:

“在此处输入图像说明”

您也可以参考此链接设置content-type。

You can refer the following code to call the API using HttpClient:

////using System.Net.Http.Headers;
////using System.Text;
using (var client = new HttpClient())
{
    var requesturi = "https://localhost:7110/api/ToDo/relativeAddress";

    var item = new TestUserViewModel()
    {
        Name = "John Doe",
        Age = 33
    };
    ////using System.Text.Json;  // use JsonSerializer.Serialize method to convert the object to Json string. 
    StringContent content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");

    //HTTP POST
    var postTask = client.PostAsync(requesturi, content);
    postTask.Wait();

    var result = postTask.Result;
    if (result.IsSuccessStatusCode)
    {
        var Content = await postTask.Result.Content.ReadAsStringAsync();

        return RedirectToAction("Privacy");
    }
}

The API method like this:

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{ 
    [HttpPost]
    [Route("relativeAddress")]
    public string GetAddress([FromBody] TestUserViewModel testUser)
    {
        return "Address A";
    }

And the result like this:

enter image description here

You can also refer this link to set the Content-Type.

你怎么这么可爱啊 2025-02-01 07:29:56

您似乎有点迷路了,我明白了。 API学习路径很奇怪,建议您观看教程(我最喜欢的
但是,如果您尽快需要代码,则可以参考以下代码。
PS:其他答案真的很好!

        using System.Net.Http;
        using System.Net.Http.Headers;
            
        public class ApiHelper
                {
                    public HttpClient ApiClient { get; set; }
            
                    public void InitializeClient()
                    {
                        ApiClient = new HttpClient();
                        ApiClient.BaseAddress = new Uri("https://mywebapisite.com/");
                        ApiClient.DefaultRequestHeaders.Accept.Clear();
                        ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    }
                    public async Task PostSomething(FormUrlEncodedContent data)
                    {
                       using (HttpResponseMessage response = await ApiClient.PostAsync("/item",data)
                       {
                         var result = await response.Content.ReadAsAsync<string>();
                         
                       }
                    }
                }

You seem a little bit lost, and I get it. Api learning path is kinda weird, I recommend you watch a tutorial (My favorite https://www.youtube.com/playlist?list=PLLWMQd6PeGY0bEMxObA6dtYXuJOGfxSPx)
But if you need code asap, you could refer the following code.
Ps: The others answers are really good!

        using System.Net.Http;
        using System.Net.Http.Headers;
            
        public class ApiHelper
                {
                    public HttpClient ApiClient { get; set; }
            
                    public void InitializeClient()
                    {
                        ApiClient = new HttpClient();
                        ApiClient.BaseAddress = new Uri("https://mywebapisite.com/");
                        ApiClient.DefaultRequestHeaders.Accept.Clear();
                        ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    }
                    public async Task PostSomething(FormUrlEncodedContent data)
                    {
                       using (HttpResponseMessage response = await ApiClient.PostAsync("/item",data)
                       {
                         var result = await response.Content.ReadAsAsync<string>();
                         
                       }
                    }
                }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文