簡體   English   中英

通過現有的 API URL 提交表格並得到 JSON 回復

[英]Submit form through existing API URL and get JSON response

我是 API 的新手,

以下是我的情況,我需要幫助的地方。 我的代碼可能有很多問題,請幫助我學習這個。 :)

我有一個現有的 API URL ,我的目標是在提交表單時向現有的 API URL 發送請求並獲得低於 JSON 的響應


{
    "success": true,
    "message": "GOOD",
    "data": null
}

.cshtml 代碼

@section Scripts {
                <script type="text/javascript">
                    $("#form1").submit(function () {
                        var Serial = $.post('http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL', $('#form1').serialize())
                            .success(function () {
                                var path = Serial.getResponseHeader('Location');
                                var i = $('<a/>', { href: path, text: path });
                                $('#message').html(i);
                            })
                            .error(function () {
                                $('#message').html("Error for changes.");
                            });
                        return false;
                    });
                    
                </script>
            }
<div>

                <form Id="form1" method="post" action="http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL" enctype="application/x-www-form-urlencoded">
                    <asp:Panel ID="pnlGrid" runat="server" Visible="true">
                        <table>

                            <tr>
                                <td style="width: 25%; height: 30px">
                                    <div>
                                        <label for="name">Special Instruction:</label>
                                        <asp:CheckBox ID="CheckBox1" runat="server" />

                                    </div>
                                </td>
                            </tr>

                            <tr>
                                <td style="width: 25%; height: 30px">
                                    <div>
                                        <label for="name" style="display: block">Notes: </label>
                                        <textarea style="display: block"></textarea>
                                    </div>
                                </td>
                            </tr>

                            <tr>

                                <td style="width: 25%; height: 30px">
                                    </br>
                                    <div>

                                        <input type="submit" value="Submit" />

                                        @*<button style="width:fit-content" name="StartRequest" value="StartRequest">Start Request</button>*@

                                    </div>
                                </td>
                                <th style="border:inherit">

                                </th>
                            </tr>
                        </table>
                    </asp:Panel>
                </form>
            </div>

CONTROLLER

using DocumentFormat.OpenXml.ExtendedProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebApplication9.Models;

namespace WebApplication9.Controllers
{

    using WebApplication9.Models;
    public class ChangesController : ApiController
    {
        static readonly Dictionary<Guid, Change> _changes = new Dictionary<Guid, Change>();
        [HttpPost]
        [ActionName("Code")]
        public HttpResponseMessage PostComplex(Change change)
        {
            if(ModelState.IsValid && change != null)
            {
                change.Notes = HttpUtility.HtmlEncode(change.Notes);
                var Id = Guid.NewGuid();
                _changes[Id] = change;
                var response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent(change.Notes)
                };
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "type", Id = Id }));
                return response;

            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }


        [HttpPost]
        [ActionName("Decode")]
        public HttpResponseMessage PostSimple([FromBody] string value)
        {
            if(value != null)
            {
                Change change = new Change()
                {
                    Notes = HttpUtility.HtmlEncode(value)
                };
                var Id = Guid.NewGuid();
                _changes[Id] = change ;
                var response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent(change.Notes)
                };
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new {action = "type", Id=Id }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        [HttpGet]
        public Change Notes(Guid Id)
        {
            Change change;
            if(_changes.TryGetValue(Id, out change))
            {
                return change;
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
        }
    }
}

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication9.Models
{
    public class Change
    {
        public string Notes { get; set; }
        
    }
}

Webapi配置文件

namespace WebApplication9
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

            );

            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }
}

我試過:通過網絡表單的提交按鈕發布現有的 API URL。 預計會得到以下回應:

{
    "success": true,
    "message": "GOOD",
    "data": null
}

但是收到以下錯誤消息: 在此處輸入圖像描述

您好@Guru,您可以添加通用的 API 響應包裝器來返回您的響應。

public class ServiceResponse<T>
 /// <summary>
/// Generic wrapper for web api response.       
/// </summary>
/// <typeparam name="T"></typeparam>
public class ServiceResponse<T>
{

    public T Data { get; set; }
    public bool Success { get; set; } = true;
    public string Message { get; set; } = null;
    public string Error { get; set; } = null;
    public List<string> ErrorMessages { get; set; } = null;
}

如何使用它:

        ServiceResponse<NoteModel> _response = new();
       
                
            _response.Success = true;
            _response.Data = NoteModel;
            _response.Message = "Created";

       
        return _response;

下面是 HttpResponseMessage 和 IHttpActionResult 的示例。 我已經測試了兩者並且它們有效。

 [HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(SampleViewModel change)
{
    if (ModelState.IsValid && change != null)
    {
        ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();

        var newGuid = Guid.NewGuid().ToString();
        change.Id = newGuid;

        if (!string.IsNullOrWhiteSpace(change.Id))
        {
            // ...
            _response.Data = change;
            _response.Success = true;
            _response.Message = "Created";
            return Request.CreateResponse(_response);
        }

        // ...
        _response.Data = change;
        _response.Success = false;
        _response.Message = "Failed";
        return Request.CreateResponse(_response);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

[HttpPost]
[ActionName("Code")]
public IHttpActionResult PostComplex2(SampleViewModel change)
{
    if (ModelState.IsValid && change != null)
    {
        ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();

        var newGuid = Guid.NewGuid().ToString();
        change.Id = newGuid;

        if (!string.IsNullOrWhiteSpace(change.Id))
        {
            // ...
            _response.Data = change;
            _response.Success = true;
            _response.Message = "Created";
            return Ok(_response);
        }

        // ...
        _response.Data = change;
        _response.Success = false;
        _response.Message = "Failed";
        return Ok(_response);
    }
    else
    {
        return BadRequest();
    }
}
public class SampleViewModel
{
    [Required]
    [MinLength(10)]
    [MaxLength(100)]
    [Display(Name = "Ask Magic 8 Ball any question:")]
    public string Question { get; set; }

    public string Id { get; set; }

    //See here for list of answers
    public string Answer { get; set; }
}

public class ServiceResponse<T>
{
    public T Data { get; set; }

    public bool Success { get; set; }

    public string Message { get; set; }

    public string Error { get; set; }

    public List<string> ErrorMessages { get; set; }
}

    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM