Im new to API,
Below is my scenario, Where i need help. My code may have many issues, kindly help me to learn this. :)
I have an existing API URL , and My objective is to POST request to that existing API URL while submitting a form and get below JSON response
{
"success": true,
"message": "GOOD",
"data": null
}
.cshtml code
@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; }
}
}
Webapiconfig.cs
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);
}
}
}
I TRIED: POST existing API URL through Submit button of a webform. Expected to get below response:
{
"success": true,
"message": "GOOD",
"data": null
}
Hi @Guru you can add generic API response wrapper to return you response.
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;
}
How to use it:
ServiceResponse<NoteModel> _response = new();
_response.Success = true;
_response.Data = NoteModel;
_response.Message = "Created";
return _response;
[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; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.