Articles → ASP .NET WEB API → Fromuri And Frombody In Web API
Fromuri And Frombody In Web API
Purpose
- In FromUri, parameter is passed as query string.
- In FromBody, parameter is passed in request body.
Scenarios Of Using Fromuri And Frombody
- If data is of simple type and there is no sensitive information then, FromURI could be used for passing parameter.
- If data is of simple type and data contains sensitive information then, FromBody should be used for parameter passing.
- If the data is of complex type or a list then, FromBody should be used for parameter passing.
Frombody Example
- Web API application
- Console application (For calling web API)
[System.Web.Http.HttpPost]
public void PassDataInBody([FromBody] string name) {
System.IO.File.WriteAllText(@"c:\test\from_body_text_file.txt", name);
}
string data = Console.ReadLine();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:1482/");
var response = client.PostAsJsonAsync("api/Test", data).Result;
Fromuri Example
[System.Web.Http.HttpGet]
public string GetSomething([FromUri] string name) {
return "Hello " + name;
}
using(var client = new WebClient()) {
client.Headers["request-type"] = "application/json";
string result = client.DownloadString("http://localhost:1482/api/Test?name='karan'");
}