My goal is to be able to call both GET and POST request from one controller, if possible. Having a private method, will allow me to pass input parameters for GET from the URI and for POST from the body. However, I am little unsure of what approach to take, in implementing the logic.
I am currently receiving an error, when calling the POST request in Fiddler --> NullReferenceException -- error --> Object reference not set to an instance of an object, inside private method call. The private method request works fine for GET URI request but not for POST request.
public static HttpContext Current { get; set; }
[HttpGet]
public HttpResponseMessage get([FromUri] Query query)
{
return method(Current, query);
}
[HttpPost]
public HttpResponseMessage post([FromBody] Query query)
{
return method(Current, query);
}
private HttpResponseMessage method(HttpContext request, Query query)
{
if (User.IsInRole("admin"))
{
IQueryable<data> Data = null;
if (!string.IsNullOrEmpty(query.name))
{
var ids = query.name.Split(',');
var dataMatchingTags = db.data.Where(c => ids.Any(id => c.Name.Contains(id)));
if (Data == null)
Data = dataMatchingTags;
else
Data = Data.Union(dataMatchingTags);
}
if (Data == null)
Data = db.data;
if (query.startDate != null)
{
Data = Data.Where(c => c.UploadDate >= query.startDate);
}
Data = Data.OrderByDescending(c => c.UploadDate);
var data = Data.ToList();
if (!data.Any())
{
var message = string.Format("No data found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Access Denied, Please try again.");
}
I have added in response code to my private method, to test the call in Fiddler and it responded back with the following result:
HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcbWlzc3lcRG9jdW1lbnRzXFZpc3VhbCBTdHVkaW8gMjAxMlxQcm9qZWN0c1xBUElfMjAxNFxUaGVhdGljYV9KdW5lMjAxNFxWM190ZXN0aW5nXEFQSV8xN09jdFxBUElfMDlPY3RcYXBpXHN1YnNldA==?=
X-Powered-By: ASP.NET
Date: Thu, 31 Jul 2014 09:40:16 GMT
Content-Length: 12
"query null"
Fiddler - Testing POST Request:
In the composer tab of the Fiddler, I copy in the URL -- [http://localhost:45361/api/subset]. In the Request header box:
User-Agent: Fiddler<br />
Content-Type: application/json;<br />
Host: localhost:45361<br />
Content-Length: 16<br />
Authorization: Basic ###########==<br />
In the Request Body box:
{"name":"store"}
How can I prevent this while making a POST request and How can I get my POST request to output data, as same as GET request.
Please help and advice.
Many thanks for your time and help.