is it possible to use out attribute in a Api Controller method? I'm using C#.
for exp:
[HttpGet]
public string GetWhatever(string type, string source,out int errorCode, out string errorMessage)
if it is, an example of how to call it and get the out value would be great.
No, this is not possible. Only the return value is used and sent to the client.
You should sent a proper HTTP status code and the error message in body. Have a look at this: http://www.asp.net/web-api/overview/error-handling/exception-handling
I believe you miss-understand the usage of the Web API.
Your Web Api method will not be called like any other C# class method, unless you access the library directly and reference the api controller and its method like any other C# class.
The method will be called via the ASP.NET action selector and that will depend on your HTTP verb (GET, PUT, POST, DELETE or PATCH) and depending on the type and the number of your parameters.
Now your method can return your data or returns error depending on your situation, but eventually all your responses will convert to statuscode/content/error,...etc which is what the HTTP protocol understands and deals with.
for example your method can return Ok Status code (200), or Notfound status code 404 depending on where your request found the requested resource or not.
You can start with this article about Web API 2, hopefully you get a better understanding.
Hope that helps.
Related
Here is my method It will take only one parameter . But I want user whaterver add in request body I need to save in logging.
[HttpPost]
[LogAPIUser]
public async Task<JsonResult> GameDetail(long game)
Here is my Postman request
In ActionExecutingContext I have got only one action parameter
How can I get all body request data?
If anyone have idea please let me know
Thanks in advance.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api states that:
At most one parameter is allowed to read from the message body.
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
You can try to look at this question:
WebAPI Multiple Put/Post parameters
basically, you read the whole body, and get your elements out of it.
something in the effect of
[HttpPost]
public string MyMethod([FromBody]JObject data)
{
long game = data["game"].ToObject<Long>();
long rer = data["rer"].ToObject<Long>();
}
(did not try code, might be buggy)
I have an third party event that post data to my hosted API but the problem is I don't know the Json structure which event posting to my API from Body. I need to read the json content posted by Event to my API.
I have tried to create post method as dynamic or string type the event able to call the service but data is not get typecast, it shows null always.
[HttpPost]
RecievedPayload([FromBody]dynamic json)
{
}
[HttpPost]
RecievedPayload([FromBody]string json)
{
}
RecievedPayload Api method is getting invoked by Third party Event but the json content is null. I need to know the Json structure so that I can make a custom class to hold the content.
There isn't a simple way to just get the whole body as a parameter.
This blog post is worth a full read: https://weblog.west-wind.com/posts/2013/dec/13/accepting-raw-request-body-content-with-aspnet-web-api
However to accomplish your goal, this is a slightly modified version of a code sample provided in the blog post, which should work for your needs:
[HttpPost]
public async Task<string> RecievedPayload()
{
string result = await Request.Content.ReadAsStringAsync();
return result;
}
Also worth reading: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
I have an ASP.NET Core API that is expecting a POST request in the shape of a particular object -- see code sample below.
I make sure that my front-end client sends the data in that exact shape. I also make sure by inspecting my call with Fiddler that the data is being sent to the API.
When the request hits the API method though, it's null.
My first thought was that the model binder is the cause of the issue. Meaning, somehow, the data I'm sending is not matching the object my API method is expecting.
I've been staring at the code for a few hours now and it seems OK to me. Assuming that the shape of the object sent by the front-end matches the object my API is expecting, what else could be causing this issue?
I've been using similar code all over my app and everything is working fine.
My code looks like this:
[HttpPost("test")]
public async Task<IActionResult> DoSomething([FromBody]MyObject data)
{
// Some logic here...
}
Here are a few things that I'm sure about:
I'm hitting the API method so there are no routing issues
The point above also confirms that my front-end client is sending a request
I know that my front-end client is sending data -- confirmed it through Fiddler
UPDATE:
This is definitely caused by model binder. I changed the code from MyObject to dynamic to see what would happen and sure enough I'm getting the data sent by the front-end. I haven't found the exact property that's causing the issue yet but I'm close. Here's what my API method looks like for now till I find the exact cause of the issue:
[HttpPost("test")]
public async Task<IActionResult> DoSomething([FromBody]dynamic data)
{
// Some logic here...
}
UPDATE 2:
Found the issue!!!!
I had a GUID property with a null valud in it and the model binder didn't like it.
This usually happens when your object can't be deserialized from JSON request.
The best practice would be to make sure that all the request properties can accept null values (make value types properties are nullable). And then you can validate that all your action needs is provided in the request and return 400 error if not.
I've been searching for this problem but non was identical to my case.
I have the following controller:
public HttpResponseMessage GetMyService(int aType, [FromUri] string streamURL)
streamURL is a parameter that gets a full URL sent by the client.
The client calls the service like that:
http://www.myservice.com/.../GetMyService/?aType=1&streamURL=http://www.client.com/?p1=100&p2=200
The problem is that at then end, I get the [FromUri] string streamURL parameter as http://www.client.com/?p1=100 without the &p2=200
This is known and reasonable, but I cannot place any encoding/decoding functionality as the URL is cut at the very beginning.
Any help would be appreciated..
THX
The client should properly URL encode the value of the streamURL query string parameter when making the request in order to conform to the HTTP protocol specification:
http://www.myservice.com/.../GetMyService/?aType=1&streamURL=http%3A%2F%2Fwww.client.com%2F%3Fp1%3D100%26p2%3D200
So basically there's nothing you could do on the server side, you should fix the client.
I have an MVC WebAPI 2 project with a Controllers controller. The Method I'm trying to call is POST (Create). I need to access the referring URL that called that method yet, no matter what object I access, the referring URL either doesn't exist in the object or is null.
For example, I've added the HTTPContext reference and the following returns null:
var thingythingthing = HttpContext.Current.Request.UrlReferrer;
The Request object does not have a UrlReferrer property.
This returns null as well:
HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]
I cannot modify the headers because I need to be able to generate a link to the method and filter access by origin of the call.
Any particular place I should be look or, alternatively, any particular reason why those are returning null?
Edit: I have a solution for GET methods (HttpContext.Current.Request.RequestContext.HttpContext.Request.UrlReferrer) but not for POST methods.
See this answer. Basically, WebAPI requests use a different kind of request object. You can create an extension method that provides a UrlReferrer for you, though. From the linked answer:
First, you can extend HttpRequestMessage to provide a UrlReferrer() method:
public static string UrlReferrer(this HttpRequestMessage request)
{
return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Then your clients need to set the Referrer Header to their API Request:
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);
And now the Web API Request includes the referrer data which you can access like this from your Web API:
Request.UrlReferrer();