Post WebApi Method With Parameter C# - c#

I would like to just post Webapi method in asp.net mvc the post action method looks like
[HttpPost]
[Route("api/agency/Dashboard")]
public HttpResponseMessage Index(getCookiesModel cookies)
{
//code here
}
and I am sending post request like this
string result = webClient.DownloadString("http://localhost:11668/api/agency/dashboard?cookies=" + cookies);
and the getCookiesModel
public class getCookiesModel
{
public string userToken { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public long userId { get; set; }
public string username { get; set; }
public string country { get; set; }
public string usercode { get; set; }
}
But this return 404 page not found.
Please help me how to solve this.

DownloadString is a GET request and since the action is expecting a POST, you can see where that may be a problem.
Consider using HttpClient to post the request. If sending the payload in the body then there is no need for the query string, so you also need to update the client calling URL.
var client = new HttpCient {
BaseUri = new Uri("http://localhost:11668/")
};
var model = new getCookiesModel() {
//...populate properties.
};
var url = "api/agency/dashboard";
//send POST request
var response = await client.PostAsJsonAsync(url, model);
//read the content of the response as a string
var responseString = await response.Content.ReadAsStringAsync();
The web API should follow the following syntax
[HttpPost]
[Route("api/agency/Dashboard")]
public IHttpActionResult Index([FromBody]getCookiesModel cookies) {
//code here...
return Ok();
}

Related

Get json data from POST method in asp.net mvc

I got an error while getting json data from POST method, am I doing something wrong
C# Code:
public IActionResult signupapi(UserSignUp user)
{
var model = new Models.SignUpModelAPI(HttpContext);
if (user == null)
{
return Content(model.ResponseJsonText(false, string.Format(model.Language("empty"),
HttpContext.Request.Method, HttpContext.Request.Path.Value), Class.CodeResponse.ERROR), new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
if (!model.isAllowMethod("POST"))
{
return Content(model.ResponseJsonText(false,string.Format(model.Language("notallowmethod"),
HttpContext.Request.Method,HttpContext.Request.Path.Value),Class.CodeResponse.ERROR),new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
return Content(JsonConvert.SerializeObject(user));
}
public class UserSignUp
{
public string fullname { get; set; }
public string username { get; set; }
public string email { get; set; }
public string password { get; set; }
}
And this is the result when i try on reqbin every value i get is null
You need to add FromBody attribute to get your data for the POST operation:
public IActionResult signupapi([FromBody]UserSignUp user)
You can read more on parameter binding on MSDN docs.

Refit saying it cant find the authentication method yet it works in swagger

I am trying to use Refit but am having an issue it says its cant find my authenticate method when trying to login a user form the client side. Refit is a strongly typed httpclient replacement. Im wondering is it cause I'm using the FromBody attribute in the swagger side?
Base url is stored in a var
public const string APIUrl = "https://localhost:44315/api";
public interface ILoginAPI
{
[Post("/Users/")]
Task<Token> Authenticate(User user);
}
My user Controller has the function defined as
[AllowAnonymous]
[HttpPost("Authenticate")]
public IActionResult Authenticate([FromBody] AuthenticateRequest model) {
var response = _userService.Authenticate(model, ipAddress());
if (response == null)
return BadRequest(new { message = "Username or password is incorrect" });
setTokenCookie(response.JwtToken);
return Ok(response);
}
My Token is here as a class
public class Token
{
public bool Authenticated { get; set; }
public string Created { get; set; }
public string Expiration { get; set; }
public string AccessToken { get; set; }
public string Message { get; set; }
}
And here is me trying to consume it its a web api project that has jwt berrer token and that functionality works as it stands.
public IActionResult Index()
{
var loginAPI = RestService.For<ILoginAPI>(Constants.APIUrl);
Token token = loginAPI.Authenticate(
new User()
{
Username = "David",
Password = "Test12345",
}).Result;
var mytokenHere = JsonConvert.SerializeObject(token);
var test = token.Authenticated;
return View();
}
Cause when I look at swagger ui all it shows me is username and passsword here which works.
Results
But why when I am attempting to do it thru refit is it not finding the api call.
You have to decorate the parameter you want to use as the body of your request with [Body] attribute
public const string APIUrl = "https://localhost:44315/api";
public interface ILoginAPI
{
[Post("Authenticate")]
Task<Token> Authenticate([Body]User user); // => parameter decorated with [Body]
}
you can look at the documentation here for more info

Call and get response from web api in a winform c# application

I am making a simple WinForm Application in Windows and I want to get some data about foreign exchange rates. So I decided to call an API from Oanda. I tried several things around but nothing worked. It gives the response in CSV as well as JSON format. I don't know which will be easier to handle.
Also for this type of response, I am unable to create its model class.
Response:
JSON:
{
"meta": {
"effective_params": {
"data_set": "OANDA",
"base_currencies": [
"EUR"
],
"quote_currencies": [
"USD"
]
},
"endpoint": "spot",
"request_time": "2019-06-08T12:05:23+00:00",
"skipped_currency_pairs": []
},
"quotes": [
{
"base_currency": "EUR",
"quote_currency": "USD",
"bid": "1.13287",
"ask": "1.13384",
"midpoint": "1.13336"
}
]
}
CSV:
base_currency,quote_currency,bid,ask,midpoint
EUR,USD,1.13287,1.13384,1.13336
I just need those three numbers so, which method will be helpful and how.
This code I already tried:
var client = new HttpClient();
client.BaseAddress = new Uri("https://www1.oanda.com/rates/api/v2/rates/");
HttpResponseMessage response = await client.GetAsync("spot.csv?api_key=<myapikey>&base=EUR&quote=USD");
string result = await response.Content.ReadAsStringAsync();
textBox1.Text = result;
Edit: I need the result of this call for my further processing so I must need this method to complete its execution before proceeding further
First creating model from Json:
use a online model generator like Json2C#, for the Json that you have posted, following is the model generated:
public class EffectiveParams
{
public string data_set { get; set; }
public List<string> base_currencies { get; set; }
public List<string> quote_currencies { get; set; }
}
public class Meta
{
public EffectiveParams effective_params { get; set; }
public string endpoint { get; set; }
public DateTime request_time { get; set; }
public List<object> skipped_currency_pairs { get; set; }
}
public class Quote
{
public string base_currency { get; set; }
public string quote_currency { get; set; }
public string bid { get; set; }
public string ask { get; set; }
public string midpoint { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public List<Quote> quotes { get; set; }
}
Now connecting to the WebAPI using HttpClient, which has the option to return both Json and CSV, I would prefer JSON being standard, which can also be consumed easily by variety of clients, use the following simple generic methods:
Assuming it is GET only call, just supply the Host and API details to the generic Process method underneath:
public async Task<TResponse> Process<TResponse>(string host,string api)
{
// Execute Api call Async
var httpResponseMessage = await MakeApiCall(host,api);
// Process Json string result to fetch final deserialized model
return await FetchResult<TResponse>(httpResponseMessage);
}
public async Task<HttpResponseMessage> MakeApiCall(string host,string api)
{
// Create HttpClient
var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }) { BaseAddress = new Uri(host) };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Make an API call and receive HttpResponseMessage
HttpResponseMessage responseMessage = await client.GetAsync(api, HttpCompletionOption.ResponseContentRead);
return responseMessage;
}
public async Task<T> FetchResult<T>(HttpResponseMessage result)
{
if (result.IsSuccessStatusCode)
{
// Convert the HttpResponseMessage to string
var resultArray = await result.Content.ReadAsStringAsync();
// Json.Net Deserialization
var final = JsonConvert.DeserializeObject<T>(resultArray);
return final;
}
return default(T);
}
How to use:
Simply call:
var rootObj = await Process<RootObject>("https://www1.oanda.com/rates/", "api/v2/rates/");
You receive the deserialized RootObject as shown in the model above
For anything further complex processing like sending input to the call with http body, above generic code needs further modification, it is currently only specific to your requirement
Edit 1: (Making the entry call Synchronous)
To make the overall call synchronous, use the GetAwaiter().GetResult() at the topmost level, Main method will be converted to, rest all will remain same as in the sample (async methods)
void Main()
{
var rootObj = Process<RootObject>("https://www1.oanda.com/rates/", "api/v2/rates/").GetAwaiter().GetResult();
}
Edit 2: (Making complete code Synchronous)
void Main()
{
var rootObj = Process<RootObject>("https://www1.oanda.com/rates/", "api/v2/rates/");
}
public TResponse Process<TResponse>(string host, string api)
{
// Execute Api call
var httpResponseMessage = MakeApiCall(host, api);
// Process Json string result to fetch final deserialized model
return FetchResult<TResponse>(httpResponseMessage);
}
public HttpResponseMessage MakeApiCall(string host, string api)
{
// Create HttpClient
var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }) { BaseAddress = new Uri(host) };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Make an API call and receive HttpResponseMessage
HttpResponseMessage responseMessage = client.GetAsync(api, HttpCompletionOption.ResponseContentRead).GetAwaiter().GetResult();
return responseMessage;
}
public T FetchResult<T>(HttpResponseMessage result)
{
if (result.IsSuccessStatusCode)
{
// Convert the HttpResponseMessage to string
var resultArray = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
// Json.Net Deserialization
var final = JsonConvert.DeserializeObject<T>(resultArray);
return final;
}
return default(T);
}
You can use an online service such as json2csharp to get your json model and Json.Net to serialise and deserialise the json string. The following models your json.
public class EffectiveParams
{
public string data_set { get; set; }
public List<string> base_currencies { get; set; }
public List<string> quote_currencies { get; set; }
}
public class Meta
{
public EffectiveParams effective_params { get; set; }
public string endpoint { get; set; }
public DateTime request_time { get; set; }
public List<object> skipped_currency_pairs { get; set; }
}
public class Quote
{
public string base_currency { get; set; }
public string quote_currency { get; set; }
public string bid { get; set; }
public string ask { get; set; }
public string midpoint { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public List<Quote> quotes { get; set; }
}
Note that you can change RootOject to a more descriptive name.
So, for example, to get the bid, ask and midpoint value for each quotes, you can simply do this:
RootObject rootObj=JsonConvert.DeserializeObject(jsonString);
//Get the required values.
foreach(var quote in rootObj.quotes)
{
Console.WriteLine($"Bid : {quote.bid} Ask: {quote.ask} MidPoint: {quote.midpoint}");
}

Sending Protobuf message to Web API Failing

I am using Microsoft Web API 2 and Protobuf-net to serialize my data. Everything is working perfectly, except when I want to send binary data to the Web API controller. I end up getting a 500 error.
Is this currently possible or is this restricted to serialization only? To verify my response was correct, I used ProtobufJS and it decoded it correctly. To pinpoint my issue, I excluded it and directly sent my response as soon as I got it. Any help getting set up would be greatly appreciated.
Web API Controller
public class UserController : ApiController
{
// GET api/<controller>
public User Get()
{
var user = new User{ Id = "ABC1", FirstName = "John", LastName = "Doe" };
return user;
}
// GET api/user/
public void Post(User user)
{
var type = "POST";
}
}
Model
[ProtoContract]
public class User
{
[ProtoMember(1)]
public string Id { get; set; }
[ProtoMember(2)]
public string FirstName { get; set; }
[ProtoMember(3)]
public string LastName { get; set; }
}
Javascript
<script>
var get = new XMLHttpRequest();
get.open("GET", "api/user", true);
get.responseType = "arraybuffer";
get.setRequestHeader("Accept", "application/x-protobuf");
get.onload = function (event) {
var arrayBuffer = get.response;
var post = new XMLHttpRequest();
post.open("POST", "api/user", true);
post.setRequestHeader("Accept", "application/x-protobuf");
post.overrideMimeType("application/x-protobuf");
post.send(arrayBuffer);
}
get.send(null);
</script>

Consuming REST API using razor MVC .net

I'm creating rest api MVC, to make model i'm using entity framework and to make my controller i'm using scaffolding item, i have my views(razor) but i dont know how to get data o how to post data from my view to my controller.
Somebody help me please!
Model
public partial class Information
{
public int ID { get; set; }
public string name { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string Email { get; set; }
}
Controller
private BaseNegociosEntities db = new BaseNegociosEntities();
// GET api/Informacion
public IEnumerable<Information> GetInformations()
{
return db.Information.AsEnumerable();
public HttpResponseMessage PostInformacion(Informacion informacion)
{
if (ModelState.IsValid)
{
db.Informacion.Add(informacion);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, information);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = information.Id_Informacion }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
You have to create list in model.
List<Information> list1=new List<Information>{get;set;}
Then need to feed data into that list from controller. So you can send your Model's list to view. Then you can serialize your list to xml or json.

Categories

Resources