你可以成功地发送HTTP请求到我的ASP.NET Core控制器。

huangapple go评论66阅读模式
英文:

How can I successfully send http requests to my ASP.NET Core controller

问题

I have built a .NET Core server that is linked up to a postgres database but what I'm attempting to do now is send requests to the server from a mobile app to execute the CRUD functions with the server. This is so the mobile can send requests that will be an object using a model that's set up in both server and mobile app to be the same. Then the server will POST that request to the database.

This code is on the mobile app that makes a baseAddress for the server and then the other code is inside a save method that turns the object into a JSON string and presumably sends it to the controller.

这是在移动应用程序上的代码,创建了一个服务器的基础地址,然后其他代码位于将对象转换为JSON字符串并将其发送到控制器的保存方法中。

private static readonly HttpClient sharedClient = new()
{
    BaseAddress = new Uri("http://10.188.144.18:5240/AandEBacklog"),
};

using StringContent jsonContent = new(JsonSerializer.Serialize(new { note }),
    Encoding.UTF8,
    "application/json");

using HttpResponseMessage response = await sharedClient.PostAsync("MobileResponse", jsonContent);

I know that I need to do something with routing in the program.cs file in the server.

我知道我需要在服务器的 program.cs 文件中对路由进行一些设置。

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

I have a controller that connects to the database but don't know whether I can use the httpRequest in that controller or if I need to send it to another one and then the other controller handles it.

我有一个连接到数据库的控制器,但不知道是否可以在该控制器中使用 httpRequest,或者是否需要将请求发送到另一个控制器,然后另一个控制器处理它。

using Microsoft.AspNetCore.Mvc;
namespace delamainServer.Controllers;

[ApiController]
[Route("[controller]")]
public class AandEBacklogController : ControllerBase
{
    //CONNECTING TO DATABASE.
    private readonly DataContext context;

    //var httpRequest = HttpContext.Request;

    public AandEBacklogController(DataContext context)
    {
        this.context = context;
    }

    //post method example to add entry
    [HttpPost]
    public async Task<ActionResult<List<AandEBacklog>> Addemrgncy(AandEBacklog booking)
    {
        context.AandEBacklogs.Add(booking);
        await context.SaveChangesAsync();

        return Ok(await context.AandEBacklogs.ToListAsync());
    }
}

Many thanks in advance.

提前感谢您。

英文:

I have built a .NET Core server that is linked up to a postgres database but what I'm attempting to do now is send requests to the server from a mobile app to execute the CRUD functions with the server. This is so the mobile can send requests that will be an object using a model that's setup in both server and mobile app to be the same. Then the server will POST that request to the database.

This code is on the mobile app that makes a baseAddress for the server and then the other code is inside a save method that turns the object into json string and presumably sends it to the controller.

private static readonly HttpClient sharedClient = new()
        {
            BaseAddress = new Uri(&quot;http://10.188.144.18:5240/AandEBacklog&quot;),
        };

using StringContent jsonContent = new(JsonSerializer.Serialize(new { note }),
                Encoding.UTF8,
                &quot;application/json&quot;);

using HttpResponseMessage response = await sharedClient.PostAsync(&quot;MobileResponse&quot;, jsonContent);

I know that I need to do something with routing in the program.cs file in the server

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

I have a controller that connects to the database but don't know weather I can use the httpRequest in that controller or if I need to send it to another one and then the other controller handles it

using Microsoft.AspNetCore.Mvc;
namespace delamainServer.Controllers;

[ApiController]
[Route(&quot;[controller]&quot;)]
public class AandEBacklogController : ControllerBase
{
    //CONNECTING TO DATABASE.
    private readonly DataContext context;

    //var httpRequest = HttpContext.Request;

    public AandEBacklogController(DataContext context)
    {
        this.context = context;
    }

    //post method example to add entry
    [HttpPost]
    public async Task&lt;ActionResult&lt;List&lt;AandEBacklog&gt;&gt;&gt; Addemrgncy(AandEBacklog booking)
    {
        context.AandEBacklogs.Add(booking);
        await context.SaveChangesAsync();

        return Ok(await context.AandEBacklogs.ToListAsync());
    }
}

Many thanks in advance

答案1

得分: 0

对于客户端部分:

var client = new HttpClient() { BaseAddress = new Uri("http://10.188.144.18:5240") };
var content = new StringContent("yourJsonString", Encoding.UTF8, "application/json");
var response = await client.PostAsync("/AandEBacklog", content);
var responseString = await response.Content.ReadAsStringAsync();

编辑:
让我们设置一个简单的GET端点:

[ApiController]
[Route("[controller]")]
public class TimeController : ControllerBase
{
    public ActionResult<string> GetCurrentTime() => $"{DateTime.Now}";
}

从浏览器验证它是否有效(例如,http://localhost:5000/Time)。
如果有效,尝试从控制台或Xamarin应用程序使用客户端:

var client = new HttpClient() { BaseAddress = new Uri("http://localhost:5000") };
var response = await client.GetAsync("/Time");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
英文:

For client part:

    var client = new HttpClient() { BaseAddress = new Uri(&quot;http://10.188.144.18:5240&quot;) };
    var content = new StringContent(&quot;yourJsonString&quot;, Encoding.UTF8, &quot;application/json&quot;);
    var response = await client.PostAsync(&quot;/AandEBacklog&quot;, content);
    var responseString = await response.Content.ReadAsStringAsync();

EDIT:
Let's setup simple GET endpoint:

[ApiController]
[Route(&quot;[controller]&quot;)]
public class TimeController : ControllerBase
{
    public ActionResult&lt;string&gt; GetCurrentTime() =&gt; $&quot;{DateTime.Now}&quot;;
}

Verify it works from browser (e.g. http://localhost:5000/Time).
If it works try client from console or Xamarin app:

var client = new HttpClient() { BaseAddress = new Uri(&quot;http://localhost:5000&quot;) };
var response = await client.GetAsync(&quot;/Time&quot;);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);

huangapple
  • 本文由 发表于 2023年2月18日 02:13:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定