Articles → ASP .NET WEB API → Fromuri And Frombody In Web API

Fromuri And Frombody In Web API






Purpose




  1. In FromUri, parameter is passed as query string.
  2. In FromBody, parameter is passed in request body.

Scenarios Of Using Fromuri And Frombody




  1. If data is of simple type and there is no sensitive information then, FromURI could be used for passing parameter.
  2. If data is of simple type and data contains sensitive information then, FromBody should be used for parameter passing.
  3. If the data is of complex type or a list then, FromBody should be used for parameter passing.

Frombody Example




  1. Web API application
  2. 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'");
}



Posted By  -  Karan Gupta
 
Posted On  -  Saturday, January 7, 2017

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250