How are you, people I need to change the response message of the return of BadRequest().
When I use the request like this, BadResquest("error: you can not pass these values")
I want to my api return something like this:
{"error: you can not pass these values"}
but the endpoint retuned this :
{"Message":"error: you can not pass these values"}
I don't want the word "Message" in my response, is there any form to overwrite or change the response?.
You're free to create what ever response message you like. see http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results
The BadRequest() helper method is just that. It's a workload reduction method that takes care of boilerplate stuff.
Related
I am currently creating a simple game that can be played from the Postman console, as a .NET Core Web API project.
I can POST data to the game from Postman without difficulty but I'm having some problems setting up a call to an external webservice at the point at which the POST is made.
What I want to do is receive a POST, and then make an external API call for some random numbers from an external service that provides random numbers.
This method would seem to need to be inside the POST method to ensure that it's triggered after each POST request and generates new numbers each time.
I have created a ProcessRandomNumbers asynchronous method using HTTPWebClient that returns a value of 'msg' (message) and then I am trying to call that method in my POST, then pars the string to numbers and assign the values and use them for calculations. However, I can't seem to access the data ('msg') returned from the method inside of my POST request?
The code inside my POST method is below:
await ProcessRandomNumbers();
if (diceRoll.Roll == true)
{
diceRoll.DiceRoll = msg;
}
Thanks for any help anyone can provide!
Looks like ProcessNumbers() only trying to get the numbers from external website, so this method can be renamed as GetRandomNumbers().
Here is the code snippet where I returned the API response back to caller:
private async Task<string> GetRandomNumber()
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("User-Agent",
".NET Foundation Repository Reporter");
return await client.GetStringAsync("https://www.random.org/integers/?num=2&min=1&max=6&col=2&base=10&format=plain");
}
In the caller assign the return value to msg field, and use it.
I have a WebAPI C# application. My GET method is defined as:
[HttpGet]
public HttpResponseMessage Get(string id)
This API retrieves some content from a database, based on a given id. Another parameter is required but it is so long that having it on the URL would not work, so I'm using the GET body to send such second parameter.
How can I retrieve it from inside the get method?
I tried
var dataOnBody = await Request.Content.ReadAsStringAsync();
but it doesn't work as the Get method is not async and I think it doesn't need to be that (I want a normal blocking function which reads the content of the body and outputs a string)
I just need a simple way to extract my string from the request body
Even if you somehow manage to do this, you will find that support is not universal. The HTTP specs say:
The GET method means retrieve whatever information (in the form of an
entity) is identified by the Request-URI.
So the data returned relies only on the URI, not anything in the body. Many libraries won't even let you send a request body during a GET.
I'm having an implementation of DelegatingHandler which basically take a request and address it to another server (http://localhost:9999/test/page.php --> http://otherSite.com/test/page.php ).
Following my question here, I now have to read the result of the page and edit it a little bit:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
string url = request.RequestUri.PathAndQuery;
UriBuilder forwardUri = new UriBuilder(_otherWebSiteBase);
forwardUri.Path = url;
HttpRequestMessage newRequest = request.Clone(forwardUri.Uri.ToString());
HttpResponseMessage responseMessage = await _client.SendAsync(newRequest);
//HERE: How to read the responseMessage.Content in string?
return responseMessage;
}
I'm trying to read the content of the message, change some parts of it(basically change all http://otherSite.com into http://localhost:9999 ) and then return it.
The issues that I'm facing:
string content =await responseMessage.Content.ReadAsStringAsync();
Doesn't returns me anything that is readeable(I'm not sure, but I've the impression it's maybe because of the compression?)
Is there a way to replace the content of the message?
I'm trying to understand this a little better. Are you simply looking to make all requests that go to that address get redirected to another address? Given that you're putting this in the delegating handler, I'm imagining this is being run for every incoming request.
If that's the case, I don't really believe this is the location to write this code. There are two other places that I think provide a cleaner solution.
In the web server:
You seem to be recreating the idea of a Reverse Proxy (https://en.wikipedia.org/wiki/Reverse_proxy) where you want one server to simply direct requests to another without the client knowing about the change. You can make this modification on the server itself. If you're using IIS, there are guides to use IIS plugins like Application Request Routing to achieve this ( http://www.iis.net/learn/extensions/url-rewrite-module/reverse-proxy-with-url-rewrite-v2-and-application-request-routing ). Other web servers also have their own solutions but I have not personally tried them.
On the route itself
On whatever Web API route would be responding to this request, you can use http status codes to tell the browser to redirect the request elsewhere.
The 3xx series were specifically made to solve this kind of problem: http://www.restapitutorial.com/httpstatuscodes.html
That said, if you still want to use the approach in the original question, you need to ensure that there is a Media-Type Formatter for the data type that is being returned. By default, Web API will only attempt to use formatters for JSON, XML, and Form-url-encoded data. If you are returning anything else, you'll need to do a little more work ( http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters ) to get the data back to manipulate it.
I'm not entirely sure how to word the title for the best. But I know I've done this before and can't seem to find out how to do this.
I have a method like this
[HttpPost]
public string doSomething()
{
string formValue = Request.Form["MyKey"];
return formValue;
}
Then I send up a fiddler POST sample request.
I put something like this in the Request body
MyKey=SomeValue
However, when I invoke fiddler I get a null formValue string.
I know i've done this before, I just can't seem to remember how to pass this information in the body of the request.
As requested, here's my comment in the form of an answer:
Possibly you forgot to set the content-type to application/x-www-form-urlencoded?
This is necessary in order for the body to be understood to be containing form data.
I must implement method in my application which will send some data (which according to api documentation should be JSON) using GET method (it is weird...). How I can do this using c sharp in windows 8 (RestSharp lib is not working there). I don't have any experience in REST clients but I have already implement other features but there data was sended by POST or DELETE methods. I have tried "tranlate" json to get like this:
JSON:
{
a = "foo",
b = "bar
}
GET URL:
__SITE__?a=foo&b=bar
But server return null values (not error). I don't know how to deal with this thing :/
Thanks for help in advance :)
If you have api you have name of param that you should send. Just convert the data into json and sind is as this param.
If you have to send json why you`re sending param a and b as 2 diffrent strings ?
remember that a GET method can be invoked by HttpClient. Just invoke the URL
Finally it turned out (in my case) that API also accepts providing data in that way: URL?a=foo&b=bar regardless of the fact that it should be json.
Long story short, I think this will be most illuminating .. it "fills in the blanks" with using HttpClient to fire JSON Formatted data at a REST API
How do you set the Content-Type header for an HttpClient request?