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>
Related
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
I would like to start by saying that I am not a developer and this is my very first time writing a code to this extend of complication (at least to me). Any help/guidance would be much appreciated.
The idea of this program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered.
I created a folder called WebAPI which will access the API and retrieve the needed information. (please see the code)
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
Employeename status = JsonConvert.DeserializeObject<Employeename>(response);
string signature = status.Signature;
return signature;
}
}
}
I also created a class called Employeename which I defined the variables (please see code)
namespace TimeSheet_Try11_Models
{
public class Employeename
{
public string Signature { get; set; }
public string FirstName { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
}
}
Problem: There are no visible errors, however, when I start debugging and enter a name in the forms application, I get the error of "System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'" for the line "var response = wc.DownloadString(uri);" in the WebAPI folder.
I'm building a REST API and testing it out using Postman. I have an end-point which works fine when I test it by sending in raw json data, but I want to expand on this endpoint and allow it to take both json data and accept a file, so I wanted to test my current endpoint without any modifications, and see if I would get back the same result when I test my API using form-data instead of JSON, but it always throws a 415 exception.
On this picture I make a request with form-data.
And here I make the request to the same endpoint but with json data
Note that I have not added any customs headers when sending the requests, the (10) you see in the top is Temporary Headers. I also tried adding Content-Type: multipart/form-data, but got the same result.
Here's the code behind
PeopleController.cs
[HttpPost]
public ActionResult<PersonDto> PostPerson(PersonForCreationDto person)
{
var personEntity = _mapper.Map<Entities.Person>(person); //Maps PersonForCreationDto to Entites.Person. This is possible because of the mapping in PeopleProfile.cs
_personLibraryRepositry.AddPerson(personEntity);
_personLibraryRepositry.Save();
var personToReturn = _mapper.Map<PersonDto>(personEntity);
return CreatedAtRoute("GetPerson",
new { personId = personToReturn.PersonId },
personToReturn);
}
PersonForCreationDto
public class PersonForCreationDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string ReasonsForBeingOnTheList { get; set; }
public ICollection<PictureForCreationDto> Pictures { get; set; }
= new List<PictureForCreationDto>();
}
PersonLibraryRepository.cs
public void AddPerson(Person person)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.PersonId = Guid.NewGuid(); //API is responsibile for creating new IDS.
foreach (var picture in person.Pictures)
{
picture.PictureId = Guid.NewGuid();
}
_context.People.Add(person);
}
In your form data, add this to the Headers
Content-Type: application/json
I am new to Web API and trying learn how to debug Web API with POSTMAN.It is working with GET request only POST request has some trouble. I am not able to trouble shoot what exactly the error is.
[HttpPost]
public HttpResponseMessage StudentDetails(Student data)
{
return new HttpResponseMessage()
{
Content = new StringContent(JArray.FromObject(data).ToString(), Encoding.UTF8, "application/json")
};
}
And Student Class is as below.
public class Student
{
public int StudentId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public string PersonalEmail { get; set; }
}
And I am trying to test the above action in POSTMAN. I added Content-Type as "application-json" and passing JSON as below .
{
StudentId :1
FirstName : 'SINI' ,
LastName :'A',
SSN : '7894300',
PersonalEmail: 'sini#gmail.com'
}
And In the POSTMAN, I gave the below URL :
http://localhost:60893/WebAPIDemo/api/Student
But it is giving me "The resource cannot be found".
Everything was perfect. I had two projects, one is web API and the other one is MVC. I forgot to keep web API as start up project.
url is not correct, change it to:
http://localhost:60893/WebAPIDemo/api/StudentDetails
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();
}