Angular 2 HTTP post to Web API without [FromBody] - asp.net-web-api

I have a sample Angular 2 code below.
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.options = new RequestOptions({ headers: this.headers });
this.http.post('/api/todo/create', JSON.stringify(todo), this.options);
I also have an API action as seen below (ASP.NET Core)
[HttpPost]
[Route("create")]
public IActionResult Create([FromBody] Todo todo)
{
return this.Ok();
}
This code works but I am not comfortable in seeing the [FromBody] attribute in the parameter. I know that for Post requests, MVC reads it from the body. But, I have been using Restangular in AngularJS before and the parameter object is sent to an API without the [FromBody] attribute.
Is there a way to just pass the object to the API action without using the [FromBody] attribute or reading the content of the request and then deserializing it to an object?

I think using the payload of a POST method is what you should do to send data to the server. You can choose the content type you want (JSON, url encoded form, ...).
That said, the Angular2 HTTP support is low-level. I mean there is no high-level API for REST. You need to set headers by your own, choose the HTTP method you want to use... I won't find something like Restangular in Angular2.
This link could help you:
https://www.quora.com/What-are-some-of-the-best-practices-for-designing-a-RESTful-API

Related

Post data in asp.net web API with header

Hi every one I am new to Asp.net Web API and I had my question post data using asp.net Web API and got my answer accepted.
This is an extension to the same question I want to post data with some header value in the Postman and my code is as follows
public HttpResponseMessage PostCustomer([FromBody] NewUser userData, string devideId)
{
//My code
return response;
}
When I hit this in Postman passing values in JSON format in BODY - raw I got message as follows
No HTTP resource was found that matches the request URI
No action was found on the controller that matches the request.
Please help me.
It looks like you have added some additional devideId string parameter to your action. Make sure that you are supplying a value to it as a query string when making the request:
POST http://localhost:58626/api/customers?devideId=foo_bar
If you don't want to make this parameter required then you should make it optional (in terms of optional method parameter in .NET):
public HttpResponseMessage PostCustomer([FromBody] NewUser userData, string devideId = null)
{
...
}
Now you can POST to http://localhost:58626/api/customers without providing a value for this parameter.
Remark: You don't need to decorate a complex object type (such as NewUser) with the [FromBody] attribute. That's the default behavior in Web API.
UPDATE: Here's how you could read a custom header:
public HttpResponseMessage PostCustomer(NewUser userData)
{
IEnumerable<string> values;
if (this.Request.Headers.TryGetValues("X-MyHeader", out values))
{
string headerValue = values.FirstOrDefault();
}
...
return response;
}

Identify angular js AJAX calls in ASP.NET MVC code

I am working on a sample application using ASP.NET MVC and AngularJS.
In server side code , I have written a Action filter attribute , and in that I need to check whether the request is a normal request(Browser) or AJAX request.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if ( filterContext.HttpContext.Request.IsAjaxRequest())
{
}
}
The method mentioned in the above code snippet "IsAjaxRequest()" is not returning TRUE in case of AJAX request made using $http Angular service.
I observed that the request does not have X-Requested-With header , and even adding the header did not solve the request.
Note : This is NOT CORS call.
So My question.
How does filterContext.HttpContext.Request.IsAjaxRequest() decide whether the request is AJAX or not?
I can check the request header(whether it has a particular header or not) and decide whether the request is AJAX or not. Is it the right and only approach?
It decides by looking whether X-Requested-With header exists or not.
You can add X-Request-With header manually to $http service.
Individual request
$http.get('/controller/action', {
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
For every request
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
You can see why it is missing from Angular

MVC: How to serialize a knockout object into a JSON property through AJAX

I'm trying to serialize a knockout object and pass it into a JSON property called multipleCharge.
This is the ajax code to send data though Get method to a mvc controller
$.ajax({
url: _url,
type: 'GET',
//data: { multipleCharge: ko.mapping.toJS(_vm)},
data: { multipleCharge : { AccountId : 2 } },
dataType: 'json'});
And this is the method
[HttpGet]
public HttpResponseMessage GetSalesInvoiceMultipleCharge
([FromUri]MultipleChargeDto multipleCharge)
{
...
}
Please, note that the ajax method has a comment line. Using the hardcoded line, it works, multipleCharge object is not null, but if I uncomment the another line, it's a bad request in my browser.
Look at this.
Any idea about what's happening. Using the Chrome console, it looks ok; so I can't identify the error.
It is may be IIS problems with very long URL.
See this Issue with URL length in IIS7 (Windows Server 2008) question and related answers.
Also see this http://www.iis.net/configreference/system.webserver/security/requestfiltering documentation.
You could try to solve this problem by editing web.config. But also you could use POST method instead of GET and send your data in request body.

The "DELETE" type of Http request does not work in WebAPI?

I have GET, PUT, POST working in my WebAPI project.
The last one of Http requests I am doing is DELeTE, BUT it does not work.
I have read through many posts in here as well as other websites, none of them. e.g.
WebAPI Controller is not being reached on DELETE command
WebAPI Delete not working - 405 Method Not Allowed
ASP.Net WebAPI Delete verb not working
ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8
http://social.msdn.microsoft.com/Forums/en-US/windowsazuredevelopment/thread/8906fd7e-a60b-484e-be63-9574b9fca44a/
etc...
Are there any workarounds?
Please help, thanks.
Update:
My back-end code:
[HttpDelete]
public HttpResponseMessage Delete(int divisionID)
{
if (divisionID != default(int))
{
var found = dc.MedicareLocalAccounts.SingleOrDefault(m => m.DivisionID == divisionID);
if (found == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
dc.MedicareLocalAccounts.Remove(found);
dc.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
Now, if I change the parameter type from int to any classes, let's say Division
Delete(Division d)
{
int divisionID = d.DivisionID;
//....the rest is same
}
In this way, it works.
But I just do not want to input the entire object as a parameter to make the DELETE method work as it is not necessary.
So do you have any other better solutions?
Web API handles simple parameter types (int) differently than complex types (classes). By default, a simple parameter is taken from the request URI, and a complex type is taken from the request body.
In your first example, the parameter name is 'divisionID' -- does this match your route variable? The default Web API route is "api/{controller}/{id}", so the parameter should be named 'id'.
A workaround would be using the AttributeRouting library. This is an extension to WebAPI and can be downloaded from nuget. With the AttributeRouting library you could e.g. implement a function with HttpGet that wil perform the delete
[GET("delete/{id}"]
function DeleteThis(int id)
{
...
}

Spring-portlet POST ajax xmlHttpRequest

Could please anybody who has experiences with processing post xmlHttpRequests with Spring DispatcherPortlet, tell me what is the best way to do it ? I'm using YUI io module and Jackson Object Mapper as an example :
#ResourceMapping(value="stuff")
public void method(ResourceResponse response){
Person person = new Person();
person.setWeight(150);
ObjectMapper mapper = new ObjectMapper();
try{
mapper.writeValue(response.getWriter(), person);
}
...
}
Ajax:
function() {
var A = AUI();
A.io("<portlet:resourceURL id="stuff" />", {
method: 'POST',
data: {
description: 'value'
}
});
}
This is the issue where you can vote up that spring-portlet environment will have the same support that common spring-mvc has. Which is #ResponseBody, data conversion to JSON etc. Now AFAIK one has to do it manually...
EDITED: Figured out the solution
PLEASE: Take a look at this issue which is better formulated https://stackoverflow.com/questions/4782971/handling-ajax-requests-with-spring-portlet
How do you construct the URL? I think you're creating a Action URL, perhaps it should be an render URL. It means, instead of <portlet:actionURL/> you should be using <portlet:renderURL/>.
Hope it helps.
I suppose the best way to respond to ajax requests in spring portlets is described in this blog post Marshal Json data using Jackson in Spring MVC with Jaxb Annotations
This also helpful Create JSON response for AJAX request in spring 3.0
Unfortunately it is not so fancy as it would be in spring-web-mvc

Resources