Bagaimana cara mengembalikan respons http khusus yang bermakna di api web inti ASP.NET

pemrograman


1


Hi I want to create middleware for Asp.net core to wrap http response that returns response like below

{

{
"count":1,"timestamp":"2021-12-18T01:13:41.2985038+05:00",
"status":"Success",
"results":[
{
"mayPrint":null,"mayEdit":null,"mayAddCopy":null,"mayDelete":null,"mayOverride":null
}
]}

Apa yang saya coba:

Saya membuat middleware tetapi memotong respons dan memberikan kesalahan tidak dapat mengurai JSON dan juga menampilkan garis miring tambahan di array hasil, ia memotong respons seperti yang terlihat di bawah ini
“tidak dapat mengurai hasil Json
“hasil”:”[{\”code\”:\”465\”,

My code below is

public class ResponseMiddleware
{
    public class ResponseClass
    {
        public int count { get; set; }

        public DateTime timestamp { get; set; }

        public string status { get; set; }

        public object results { get; set; }
        public string ErrorMessage { get; set; }
    }
    private readonly RequestDelegate _next;
    public ResponseMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (IsSwagger(context))
            await this._next(context);
        else
        {
            var existingBody = context.Response.Body;
            using (var newBody = new MemoryStream())
            {
                context.Response.Body = newBody;
                await _next(context);
                var newResponse = await FormatResponse(context.Response);
                context.Response.Body = new MemoryStream();
                newBody.Seek(0, SeekOrigin.Begin);
                context.Response.Body = existingBody;
                var newContent = JsonConvert.DeserializeObject(new StreamReader(newBody).ReadToEnd());

                // Send modified content to the response body.
                //
                await context.Response.WriteAsync(newResponse);
            }
        }
            
    }

    private bool IsSwagger(HttpContext context)
    {
        return context.Request.Path.StartsWithSegments("/swagger");
    }
    private async Task<string> FormatResponse(HttpResponse response)
    {
        //We need to read the response stream from the beginning...and copy it into a string...I'D LIKE TO SEE A BETTER WAY TO DO THIS
        //
        response.Body.Seek(0, SeekOrigin.Begin);
        var content = await new StreamReader(response.Body).ReadToEndAsync();
        var Response = new ResponseClass(); 
        Response.status = response.StatusCode==200? "success": "Error";
        if (!IsResponseValid(response))
        {
            Response.ErrorMessage = content;
        }
        else
        {
            Response.results = content;
        }
        Response.count = response.ToString().Length;
        var json = JsonConvert.SerializeObject(Response);

        //We need to reset the reader for the response so that the client an read it
        response.Body.Seek(0, SeekOrigin.Begin);
        return $"{json}";
    }

    private bool IsResponseValid(HttpResponse response)
    {
        if ((response != null)
            && (response.StatusCode == 200
            || response.StatusCode == 201
            || response.StatusCode == 202))
        {
            return true;
        }
        return false;
    }
}

Solution 23

To create a custom HTTP response in ASP.NET Core, you can use the ObjectResult class. The ObjectResult class allows you to return a custom object as the response from a controller action.

Here’s an example of how you might use the ObjectResult class to return your custom response:

public class MyController : ControllerBase
{
    [HttpGet]
    publik IActionResult Dapatkan() {
        //  Buat objek respons khusus
        dulu tanggapan = baru
        { hitungan = 1stempel waktu = TanggalWaktu.UtcSekarang, status = "Kesuksesan"hasil = baru[]
            {
                baru
                { mungkinCetak = (bodoh?)batalmungkinEdit = (bodoh?)batalmungkinTambahkanSalinan = (bodoh?)batalmungkinHapus = (bodoh?)batalmayOverride = (bodoh?)batal
                } } };

        //  Kembalikan respons khusus menggunakan kelas ObjectResult
        kembali baru ObjectResult(respon);  } }

Ini akan mengembalikan respons HTTP khusus dengan format berikut:

{
  "count": 1,
  "timestamp": "2021-12-18T01:13:41.2985038+05:00",
  "status": "Success",
  "results": [
    {
      "mayPrint": null,
      "mayEdit": null,
      "mayAddCopy": null,
      "mayDelete": null,
      "mayOverride": null
    }
  ]
}

Anda kemudian dapat menggunakan respons khusus ini di API web ASP.NET Core sesuai kebutuhan. Ingatlah bahwa ini hanyalah sebuah contoh, dan Anda mungkin perlu menyesuaikan kode agar sesuai dengan kebutuhan spesifik Anda.

コメント

タイトルとURLをコピーしました