Custom response in place of "error": "invalid_grant" - json

I'm using oAuth 2.0 in ASP.NET web API.
In refresh token provider class I have code like this.
public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
string tokenId = context.Token;
var protectedTicket = WebApiBusiness.GetProtectedTicket(tokenId);
if (!string.IsNullOrEmpty(protectedTicket))
{
context.DeserializeTicket(protectedTicket);
var result = WebApiBusiness.RemoveRefreshToken(tokenId);
}
else
{
context.Response.ContentLength = 200;
context.Response.ContentType = "application/json";
var ML_DefaultRes = new ML_DefaultRes()
{
ResponseCode = ResponseCodes.TokenInvalidRC,
APIVersion = apiversion,
ErrorDescription = ResponseCodes.GetRCDescription(ResponseCodes.TokenInvalidRC)
};
string str = JsonConvert.SerializeObject(ML_DefaultRes);
context.Response.Write(str);
return;
}
}
When refresh token is not valid I want custom response in JSON format.
But instead of setting content length to 200 it is taking content length upto 25 only, which makes invalid JSON response.
Is their any way to make this happen?

Related

Why 2 Different JSON Results with String Parameter Search using RestSharp?

If I hard code the band name in my client request with RestSharp I get the results I expect. If I pass in the String I get a different result set. I checked the url it formed and they are the same. Any ideas? I don't use both, I will comment one out and use the other for testing this scenario.
ArtistInfoResponse IMusicRepository.GetArtistResponse(string artistName)
{
var client = new RestClient($"https://api.deezer.com/search?q=artist:{artistName}");
// returns this as url https://localhost:44343/Home/ArtistInformation?artistName=Dave%20Matthews%20Band
var client = new RestClient($"https://api.deezer.com/search?q=artist:\"Dave Matthews Band\"");
// returns this in url https://localhost:44343/Home/ArtistInformation?artistName=Dave%20Matthews%20Band
var request = new RestRequest(Method.GET);
var cancellationTokenSource = new CancellationTokenSource();
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
// Deserialize the string content into JToken object
var content = JsonConvert.DeserializeObject<JToken>(response.Content);
// Deserialize the JToken object into our ArtistInfoResponse Class
return content.ToObject<ArtistInfoResponse>();
}
return null;
}

i cant send json to asp mvc using angularjs

im trying to send json parameter to asp request handler like this:
$scope.SaveCarUpgrades = function () {
var parameter = JSON.stringify(resultCarUpgrades);
$http.get("/ProfileEditor/saveUserCarUpgrades/" + $scope.useridCarUpgrades,
{ params: { name: parameter }}
).then(onsuccess, onfail);
function onsuccess(response) {
if (response.status == 200) {
$scope.saveUpgradesResult = "save upgrades success";
} else {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
}
}
function onfail(response) {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
// $scope.saveUpgradesResult = parameter;
}
}
c# request handler is something very simpe. its just for testing right now:
public string SaveUserCarUpgrades(string id)
{
string result = id;
var data = Request.QueryString["name"];
return id;
}
the problem is i always get 404 if if use json as parameter. (its a complex long json) but as simple json or simple string the response is fine. i dont think the problem is mime type as i set it in iis express in devcmd.
thank you for helping

Submitting File and Json data to webapi from HttpClient

I want to send file and json data from HttpClient to web api server.
I cant seem to access the json in the server via the payload, only as a json var.
public class RegulationFilesController : BaseApiController
{
public void PostFile(RegulationFileDto dto)
{
//the dto is null here
}
}
here is the client:
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiHost"]);
content.Add(new StreamContent(File.OpenRead(#"C:\\Chair.png")), "Chair", "Chair.png");
var parameters = new RegulationFileDto
{
ExternalAccountId = "1234",
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
content.Add(new StringContent(serializer.Serialize(parameters), Encoding.UTF8, "application/json"));
var resTask = client.PostAsync("api/RegulationFiles", content); //?ApiKey=24Option_key
resTask.Wait();
resTask.ContinueWith(async responseTask =>
{
var res = await responseTask.Result.Content.ReadAsStringAsync();
}
);
}
}
this example will work:HttpClient Multipart Form Post in C#
but only via the form-data and not payload.
Can you please suggest how to access the file and the submitted json And the file at the same request?
Thanks
I have tried many different ways to submit both file data and metadata and this is the best approach I have found:
Don't use MultipartFormDataContent, use only StreamContent for the file data. This way you can stream the file upload so you don't take up too much RAM on the server. MultipartFormDataContent requires you to load the entire request into memory and then save the files to a local storage somewhere. By streaming, you also have the benefit of copying the stream into other locations such as an Azure storage container.
This solves the issue of the binary data, and now for the metadata. For this, use a custom header and serialize your JSON into that. Your controller can read the custom header and deserialize it as your metadata dto. There is a size limit to headers, see here (8-16KB), which is a large amount of data. If you need more space, you could do two separate requests, one to POST the minimum need, and then a PATCH to update any properties that needed more than a header could fit.
Sample code:
public class RegulationFilesController : BaseApiController
{
public async Task<IHttpActionResult> Post()
{
var isMultipart = this.Request.Content.IsMimeMultipartContent();
if (isMultipart)
{
return this.BadRequest("Only binary uploads are accepted.");
}
var headerDto = this.GetJsonDataHeader<RegulationFileDto>();
if(headerDto == null)
{
return this.BadRequest("Missing X-JsonData header.");
}
using (var stream = await this.Request.Content.ReadAsStreamAsync())
{
if (stream == null || stream.Length == 0)
{
return this.BadRequest("Invalid binary data.");
}
//save stream to disk or copy to another stream
var model = new RegulationFile(headerDto);
//save your model to the database
var dto = new RegulationFileDto(model);
var uri = new Uri("NEW URI HERE");
return this.Created(uri, dto);
}
}
private T GetJsonDataHeader<T>()
{
IEnumerable<string> headerCollection;
if (!this.Request.Headers.TryGetValues("X-JsonData", out headerCollection))
{
return default(T);
}
var headerItems = headerCollection.ToList();
if (headerItems.Count() != 1)
{
return default(T);
}
var meta = headerItems.FirstOrDefault();
return !string.IsNullOrWhiteSpace(meta) ? JsonConvert.DeserializeObject<T>(meta) : default(T);
}
}

Send Cookies with HTTPWebRequestion through WP8 App

I have to send the cookies to server for every subsequent HTTPWebRequest. My code goes below.
class APIManager
{
CookieContainer cookieJar = new CookieContainer();
CookieCollection responseCookies = new CookieCollection();
private async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
cookieJar = request.CookieContainer;
responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
public async Task<string> Get(string path)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.CookieContainer = cookieJar;
return await httpRequest(request);
}
public async Task<string> Post(string path, string postdata)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.Method = "POST";
request.CookieContainer = cookieJar;
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
return await httpRequest(request);
}
}
Every time i ask for the question people say that i have to set the cookie container with request by following code line.
request.CookieContainer = cookieJar;
and i used it but still server returns the 'token does not match' error. Do i need to talk to the vendor for it?
Following image shows my problem and requirement.
I haven't seen you do something with the cookieJar !
//Create the cookie container and add a cookie.
request.CookieContainer = new CookieContainer();
// This example shows manually adding a cookie, but you would most
// likely read the cookies from isolated storage.
request.CookieContainer.Add(new Uri("http://api.search.live.net"),
new Cookie("id", "1234"));
cookieJar in your APIManager is a member, everytime your instance APIManager, the cookieJar is a new instance. you need to make sure cookieJar contains what the website needs.
you can have a look at this How to: Get and Set Cookies

How to send/post the JSON request in windowsphone

Anyone knows how to send the request using JSON content in windowsphone. I had the JSON parameters how to post it.
Simply serialize the data in JSON, and write it as a POST request to the server. Here's how I do it in one of my apps:
private static IObservable<T> GetDataAsync<T, TRequest>(TRequest input, string address)
{
var request = HttpWebRequest.Create(address);
request.Method = "POST";
var getRequestStream = Observable.FromAsyncPattern<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream);
var getResponse = Observable.FromAsyncPattern<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse);
return getRequestStream()
.SelectMany(stream =>
{
try
{
using (var writer = new StreamWriter(stream))
writer.WriteLine(JsonConvert.SerializeObject(input));
}
catch
{
// Intentionally ignored.
}
return getResponse();
})
.Select(webResponse =>
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
});
}