I'm developing a web service, using WEB .API. I'm following the example, which include:
public HttpResponseMessage PostProduct(Product item)
{
item = repository.Add(item);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
for creating a POST method, allowing a client to send data in POST in ordert to insert these data in the database (I'm using Entity Framework).
What I want do, however, is slightly difference, since the data I want pass in post to the web service are not associated to any object of database: I have some data that should be write in more then one table. For example:
{"activity":"sport","customValue":"22","propertyIndex":"122-x"}
The activty value (sport) should be writed on one table, while the others two parameters (customValue e properyIndex) shouldbe writed on another table.
So I think I need to parse the json file received in POST and then execute the two insert operation.
How can I perform this task?
You need to create an object in web API project with Activity, CustomValue, PropertyIndex properties:
public class MyTestClass
{
public string Activity { get; set; }
public string CustomValue { get; set; }
public string PropertyIndex { get; set; }
}
and HttpPost will be:
[HttpPost]
public HttpResponseMessage Post(MyTestClass class)
{
// Save Code will be here
return new HttpResponseMessage(HttpStatusCode.OK);
}
Product class should have Activity, CustomValue and PropertyIndex properties to get bind with posted data.
[HttpPost]
[ActionName("alias_for_action")]
public HttpResponseMessage PostProduct([FromBody] Product item)
{
//your code here
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent("Your Result")
};
return response;
}
Yes if you want to update two tables in database using Entity Framework then you have to execute two insert operations.
Related
I am new to web API ,Here sending the form data from Angular 4 application to web API.
the form data contains a user registration details as mFormData and the user image as mImage .
I want to store the image in the system folder ex : D:/uplodedImages
and need to store all the user details in database .
I am struggling to do the above things .
service.ts(angular 4)
CreateNewComitteeMember(mFormData, mImage) {
const formData: FormData = new FormData();
formData.append('ImageFile', mImage, mImage.name);
formData.append('mFormData', JSON.stringify(mFormData));
return this.http.post(this.BASE_URL + `/api/CreateNewComitteeMember`, formData)
}
API
[AllowAnonymous]
[HttpPost]
[Route("api/CreateNewComitteeMember")]
public Task<HttpResponseMessage> CreateNewComitteeMember()
{
//How to do the remaining things here.
}
can anyone help me to solve this .
You can simply get the data by accessing the name that you used while appending your data.
But since java object will not be recognized by ASP.NET. You will need to serialize the "mFormData". So, the request will change like this.
formData.append('mFormData', JSON.stringify(mFormData));
Now in you Web API create a model that replicates your "mFormData", lets call it MFormData.
Example,
public class MFormData
{
public string Name {get; set;}
public int Age {get; set;}
public string Xyz {get; set;}
public string ImageUrl {get; set;}
...
}
Now, In your API you can access the data like this.
[AllowAnonymous]
[HttpPost]
[Route("api/CreateNewComitteeMember")]
public Task<HttpResponseMessage> CreateNewComitteeMember()
{
var imageData = HttpContext.Current.Request.Params["mImage"];
var formData = new JavaScriptSerializer()
.Serialize<MFormData>(HttpContext.Current.Request.Params["mFormData"]);
try
{
//Function to save the file and get the URL
formData.ImageUrl = new ApplicationBussinessLayer().SaveFileInDir(imgeData);
//Function to save data in the DB
var saveData = await new AppicationBussinessLayer().SaveUserInfo(formData);
}
catch(Exception ex)
{
return Request.Create(HttpStatusCode.Code, "Some error");
}
return Request.Create(HttpStatusCode.OK, "Data Saved");
}
I need to call this method in MVC controller and pass the UpdateRequest object as json format. how I can do that?
[HttpPost]
[Route("updatecertificate")]
public void updatecertificate([FromBody] UpdateRequest certificatereviewed)
{
loansRepository.updatecertificate(certificatereviewed.Id, certificatereviewed.CertificateReview);
}
and this is the input class:
public class UpdateRequest {
public int Id { get; set; }
public bool CertificateReview { get; set;}
}
this is how I call and send separate variable but now I like to send the class object in json format.
private async Task UpdateFundingCertificateReviewed(int id, bool fundingCertificateReviewed)
{
await httpClient.PostAsync(string.Format("{0}/{1}", LoanApiBaseUrlValue, updatecertificate),null);
}
I personally like Newtonsoft.Json to serialize the object.
private async Task UpdateFundingCertificateReviewed
(int id, bool fundingCertificateReviewed)
{
using (var client = new HttpClient())
{
var url = string.Format("{0}/{1}", LoanApiBaseUrlValue, updatecertificate);
var updateRequest = new UpdateRequest { Id = 1, CertificateReview = true};
var data = JsonConvert.SerializeObject(updateRequest);
await client.PostAsync(url, data);
}
}
FYI: Async without return is not a good practice. However, it is out of the original question.
If you want to transform an object into a JSON string, see this question: Turn C# object into a JSON string in .NET 4
var json = new JavaScriptSerializer().Serialize(obj);
Is this what you are after or do you want to know how to construct the http request with a JSON object in the body?
your questionis not very clear, what is the outcome that you expect ?
If you want to POST an request with JSON body you can check the #Win comment,
however if you want to make an Response from the Api to the MVC project you should do a bit more steps tough. :))
this is my first question, so I apologize if I mess up the formatting or do this wrong in general, feel free to give me pointers, I'm always open to learn.
Anyway, my issue at hand is that I have a web application I'm working on using ASP.NET 5 and MVC 6, all up to date, and so far for testing, I've been using the localdb and working with fake data. Now, I have a url, with an API token, and login info, and I am using a WebRequest to get the data and stream it with a StreamReader into a variable, writing it, and then trying to return it.
WebRequest req = WebRequest.Create(#"https://url.fortheapi.com/api/search/things?criteria=" + userInput);
req.Method = "GET";
req.Headers["username"] = "user";
req.Headers["password"] = "password";
req.Headers["token"] = "token";
StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();
Response.WriteAsync(responseData);
return View(responseData);
Here is where I'm stuck because I am not sure exactly how to pass it to the view as model data, I have no model currently, and I want to make one based on this database and use Entity Framework to work with it like I have been with the localdb. If there's a better way to do it, please feel free to present it. I will accept all the help I can get right now.
You need to create POCO classes to represent the data you receive from your api call. Once you get the response data, you may simply use a javascript serialize to deserialize the response to an object of your POCO class. You can pass this to your view.
public async Task<ActionResult> Contact()
{
var req = WebRequest.Create(#"yourApiEndpointUrlHere");
var r = await req.GetResponseAsync().ConfigureAwait(false);
var responseReader = new StreamReader(r.GetResponseStream());
var responseData = await responseReader.ReadToEndAsync();
var d = Newtonsoft.Json.JsonConvert.DeserializeObject<MyData>(responseData);
return View(d);
}
Assuming your api returns json data like this
{ "Code": "Test", "Name": "TestName" }
and you have created a POCO class called MyData which can be used to represent the data coming back from the api. You may use json2csharp to generate your C# classes from the json response you received from your api.
public class MyData
{
public string Code { get; set; }
public string Name { set;get;}
//Add other properties as needed
}
Now your view should be strongly typed to this POCO class
#model MyData
<h2>#Model.Code</h2>
<h2>#Model.Name</h2>
If what you are receiving is JSON, you can accomplish this is many ways.
One would be to wrap the code you've posted into a JSON Result typed Action. A very simplistic example below:
[HttpPost]
public JsonResult GetIncidentId(int customerId, string incidentNumber)
{
JsonResult jsonResult = null;
Incident incident = null;
try
{
incident = dal.GetIncident(customerId, incidentNumber);
if (incident != null)
jsonResult = Json(new { id = incident.Id });
else
jsonResult = Json(new { id = -1 });
}
catch (Exception exception)
{
exception.Log();
}
return jsonResult;
}
Calling it via Javascript from the view and manually populating your form (meh).
Or more elegantly, you could create an MVC model to hold the data you receive and serialise the JSON into that model. An example of which is below:
From: http://www.newtonsoft.com/json/help/html/deserializeobject.htm
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Hope this helps and good luck with your app!
I have Web API service deployed and and consuming in another web application. Web API method take complex object (List object) and results also complex object.
So I created local models for Input parameter and results model to match with Web API complex objects in web application. then I passed JsonConvert.SerializeObject for that parameter. But when I debug in Web API that parameter value showing null.
Web application
[Serializable]
public class PreferencesInput
{
public string ShortName { get; set; }
public string ShortNameDescription { get; set; }
.....
}
[Serializable]
public class PreferencesOuput
{
public bool Status { get; set; }
public string Error { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
RunAsync().Wait();
return View();
}
private static async Task RunAsync()
{
var inputs = new List<PreferencesInput>();
var input = new PreferencesInput
{
ShortName = "REGION",
ShortNameDescription = "Geographical regions",
OptedInFlag = true
};
inputs.Add(input);
....
...
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:8585/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = await client.GetAsync("preferences/updatepreferences/?id='3016523'
&optInInterestAreas=" + JsonConvert.SerializeObject(inputs) +
"&solicitationFlag=false").ConfigureAwait(false);;
if (response.IsSuccessStatusCode)
{
string results = await response.Content.ReadAsStringAsync();
var myList = JsonConvert.DeserializeObject<List<PreferencesOuput>>(results);
}
web API
[Route("preferences/updatepreferences")]
[HttpGet]
public PreferencesOuput UpdatePreferences(string id, IEnumerable<PreferencesInput> optInInterestAreas, bool solicitationFlag)
{
.....
}
Only difference is Web application Input model has less parameters than the Web API model.
What I am doing wrong here?
IEnumerable<PreferencesInput> optInInterestAreas is null
update
I can see serialization date like below before sending to Web API call, In Web API method it is showing null, rest of the parameters are showing correct.
[{"ShortName":"REGION","ShortNameDescription":"Geographical regions","ShortSubName":null,"Description":null,"OptedInFlag":true},
{"ShortName":"REGION","ShortNameDescription":"Asia Pacific","ShortSubName":"ASIA_PACIFIC","Description":null,"OptedInFlag":true},
{"ShortName":"REGION","ShortNameDescription":"Canada","ShortSubName":"CANADA","Description":null,"OptedInFlag":true}]
You could try to specify the route with parameters. Something like:
[Route("preferences/updatepreferences/{id}/{optInInterestAreas}/{solicitationFlag:bool}")]
Your optInInterestAreas parameter is null because in Web API, the parameter binding rules specify that anything other than a "simple" parameter type (string, int, etc) is assumed to be passed in the body, not the route or query string as you're doing. You could get this to work by using the [FromUri] attribute on that parameter or by defining a custom type converter, but I would highly recommend changing your API as it does not follow generally accepted best practices.
By convention, GET is assumed to be side-effect-free, but I'm guessing something called UpdatePreferences almost certainly changes data. I would consider using a different verb and passing the updated preferences in the body. POST is better, but if you want it to be truly RESTful, you should ensure that the URI uniquely identifies the resource and use PUT.
I would start by changing your input model to something like this:
public class PreferencesInput
{
public IList<InterestArea> InterestAreas { get; set; }
public bool SolicitationFlag { get; set; }
}
public class InterestArea
{
public string ShortName { get; set; }
public string ShortNameDescription { get; set; }
...
}
Then define your API action like this:
[Route("preferences/{id}")]
[HttpPut]
public PreferencesOuput UpdatePreferences(string id, PreferencesInput preferences)
{
...
}
As you can see, the URI now uniquely identifies the thing, and the verb specifies what you want to "do"; in this case, completely replace whatever is at that URI (if anything) with the thing you are passing.
Side-note:
On the MVC side, calling Wait() in your Index action is blocking a thread while waiting for your async method to complete. That's a serious invitation for deadlocks. Async only works properly if you go "all the way" with it. In this case it's incredibly easy - just change the Index action to:
public async Task<ActionResult> Index()
{
await RunAsync();
return View();
}
I'm used to doing this in Django (similar to Ruby on Rails) where in some cases I need to hard code a JSON response object for the client to be able to interpret, but I've been searching everywhere online on figuring out how to do this with ASP.NET web API and I can't find anything on this, ASP.NET web API seems to be forcing me to create a class to represent a JSON response for every URI controller.
For example, here's the only way I know for manually creating a JSON response:
1.) I first need to create the class to represent the response object
public class XYZ_JSON
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
}
2.) Then I need to properly write up the URI controller that'll return an "XYZ_JSON" that I've just defined above:
// GET: api/ReturnJSON
public XYZ_JSON Get()
{
XYZ_JSON test = new XYZ_JSON { PropertyName = "Romulus", PropertyValue = "123123" };
return test;
}
Will result with an http response of something like:
200 OK
{"PropertyName":"Romulus", "PropertyValue":"123123"}
This whole class to JSON design pattern is cool and all, but it's not helpful and actually makes things much worse when trying to return a class as a JSON object with many classes within it such as:
public class XYZ_JSON
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
public List<ComplexObject> objects { get; set; } // <- do not want
}
The JSON response object above isn't that complex, but for what I'm trying to accomplish I'll have to put a list of classes within a list of classes within a list of classes, and I can't develop it in this awkward way unless I spend a week on it which is just ridiculous.
I need to be able to return a JSON response in this kind of fashion:
// GET: api/ReturnJSON
public JSON_Response Get(string id)
{
// do some SQL querying here to grab the model or what have you.
if (somethingGoesWrong = true)
return {"result":"fail"}
else
return {"result":"success","value":"some value goes here"}
}
The design pattern above is what I'm trying to accomplish with ASP.NET web API, a very simply way to return a semi-hard coded JSON response object which would allow me to return very unique and dynamic responses from a single URI. There's going to be many use cases where a list of up to 8 completely unique Class objects will be returned.
Also, If what I'm trying to accomplish is the backwards way of doing things than that's fine. I've released a very successful and stable iOS application with a flawless Django backend server handling things this way perfectly without any issues.
Can someone explain to me how I can return a simple hard coded JSON response using the ASP.NET web API?
Thanks!
You can create anonymous types in C#, so you can use one of these to produce your hard-coded result. For example:
return new JsonResult
{
Data = new
{
result = "success",
value = "some value"
}
};
To clarify, the above code is for ASP.NET MVC. If you're using Web API, then you can just return the data object, or use an IHttpActionResult. The anonymous type part (the new {}) stays the same.
Use an anonymous object.
public object Get(string id)
{
// do some SQL querying here to grab the model or what have you.
if (somethingGoesWrong = true)
return new {result = "fail"}
else
return new {result = "success", value= "some value goes here"}
}
You can use a generic JObject to return your values without constructing a complete class structure as shown below
public JObject Get(int id)
{
return JsonConvert.DeserializeObject<JObject>(#"{""result"":""success"",""value"":""some value goes here""}");
}
For hard coded response, why not just do something like below. The JSON content will be returned without being surrounded by quotation marks.
public HttpResponseMessage Get()
{
string content = "Your JSON content";
return BuildResponseWithoutQuotationMarks(content);
}
private HttpResponseMessage BuildResponseWithoutQuotationMarks(string content)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(content);
return response;
}
private HttpResponseMessage BuildResponseWithQuotationMarks(string content)
{
var response = Request.CreateResponse(HttpStatusCode.OK, content);
return response;
}
// GET: api/ReturnJSON
public JsonResult Get()
{
return Json(new { Property1 = "Value1", Property2 = "Value2" });
}
You can return json using JsonResult class. and the Json() method takes anonymous object so you don't need to create a class.