send value from Angular service App to C# backend controller - c#

I'm getting absolutely insane with this, I've tried almost everything and can't find a way to pass a string value from a service to backend to return Json result based on that string.
Here's the problem, I have a backend that cooks all the JSON with meta-info that
frontend provides, and then return them to the frontend to display, on this case I have to get a JSON that's based on a filter that is made by a string inserted in frontend but can't find a way to pass the string to the backend, and I don't want to pass it through the URL.
Here's my code:
angular typescript service: I want to pass the "whr"
getAdvancedFilterResult(concept: string, whr: string): Promise<any> {
const headers: Headers = new Headers({
'Content-Type': 'application/json'
});
this.authService.getAuthorizationHeader(headers);
headers.append('IdLng', this.config.idLanguage);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
return this.http.get(this.config.apiDomain + this.config.apiEndpointEntities + '/' + concept + '/' + "filtered",
options
)
.toPromise()
.then(
response => response.json() as any[]
)
.catch((error) => this.customHandleError(error, this.toastrService));
}
Backend controller:
[Route("api/Entities/{entity}/filtered/")]
public HttpResponseMessage GetFilter(string entity) {
HttpResponseMessage response = new HttpResponseMessage();
string action = "READ";
//Check Authorization
AuthorizationResponse authResponse = AuthProvider.CheckAuthorization(new AuthorizationRequest() {
SCode = UserUtils.GetUserSCode(User),
ConceptString = entity,
ActionString = action,
UserId = UserUtils.GetUserID(User),
ExtraParameters = new AuthorizationRequest.ExtraParamaters() {
IdsOnly = false, Where = "!!!!!WHR HERE!!!!"
}
});
if (authResponse.IsAuthorized) {
//code
response = Request.CreateResponse(HttpStatusCode.OK, json);
} else {
response = Request.CreateResponse(HttpStatusCode.Unauthorized);
}
return response;
}
Should I pass it through the header, with headers.append('whr', whr);, that goes into the options on http.get or into body with options.body = whr;?
Also, how can I get it on the backend side to use?

You should pass the Headers like this:
getAdvancedFilterResult(concept: string, whr: string): Promise<any> {
this.authService.getAuthorizationHeader(headers);
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('x-corralation-id', '12345');
headers = headers.append('IdLng', this.config.idLanguage);
headers = headers.append('whr', whr);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
return this.http.get(this.config.apiDomain + this.config.apiEndpointEntities + '/' + concept + '/' + "filtered",
options
)
.toPromise()
.then(
response => response.json() as any[]
)
.catch((error) => this.customHandleError(error, this.toastrService));
}
To get the headers on the Server Side try this:
[Route("api/Entities/{entity}/filtered/")]
public HttpResponseMessage GetFilter(string entity) {
var request = Request;
var headers = response.Headers;
HttpResponseMessage response = new HttpResponseMessage();
string action = "READ";
var whrHeader = headers.Contains("whr") ? request.Headers.GetValues("whr").First() : ""
AuthorizationResponse authResponse = AuthProvider.CheckAuthorization(new AuthorizationRequest() {
SCode = UserUtils.GetUserSCode(User),
ConceptString = entity,
ActionString = action,
UserId = UserUtils.GetUserID(User),
ExtraParameters = new AuthorizationRequest.ExtraParamaters() {
IdsOnly = false,
Where = whrHeader
}
});
if (authResponse.IsAuthorized) {
//code
response = Request.CreateResponse(HttpStatusCode.OK, json);
} else {
response = Request.CreateResponse(HttpStatusCode.Unauthorized);
}
return response;
}

I got the solution, thanks to SiddAjmera!!
At frontend service:
getAdvancedFilterResult(concept: string, whr: string): Promise<any> {
let headers: Headers = new Headers();
this.authService.getAuthorizationHeader(headers);
headers.append('Content-Type', 'application/json');
headers.append('IdLng', this.config.idLanguage);
headers.append('whr', whr);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
return this.http.get(
this.config.apiDomain + this.config.apiEndpointEntities + '/' + concept + '/' + "filtered",
options
)
.toPromise()
.then(
response => response.json() as any[]
)
.catch((error) => this.customHandleError(error, this.toastrService));
}
And then on the backend, just used the UserUtils already made to get the header which has the value 'whr' and pass it through a function.
UserUtilis.cs:
public static string Where(HttpRequestMessage re) {
string whereCLause = "";
var headers = re.Headers;
if (headers.Contains("whr")) {
whereCLause = headers.GetValues("whr").First();
} else {
whereCLause = " ";
}
return whereCLause;
}
And Controller.cs
...
var re = Request;
HttpResponseMessage response = new HttpResponseMessage();
string action = "READ";
//Check Authorization
AuthorizationResponse authResponse = AuthProvider.CheckAuthorization(new AuthorizationRequest() {
SCode = UserUtils.GetUserSCode(User),
ConceptString = entity,
ActionString = action,
UserId = UserUtils.GetUserID(User),
ExtraParameters = new AuthorizationRequest.ExtraParamaters() {
IdsOnly = false, Where = UserUtils.Where(re)
}
});
...

Related

How to upload excel file via fetch use ASP.Net Core an React.js

I have developed a test module for generating excel file from json format.
const bodyParser = require('body-parser');
const json2xls = require("json2xls");
const fs = require('fs/promises');
const app = express();
app.use(json2xls.middleware);
app.use(bodyParser.json())
app.post("/", (req, res) => {
if(req.query.token !== "----") res.send(JSON.stringify({isError: true, inf: "Token not valide!"}));
console.log(req.body.DataList);
var xlsq = json2xls(req.body.DataList);
fs.writeFile('data.xlsx', xlsq, 'binary');
res.xls(req.query.name + new Date().toLocaleDateString() + ".xlsx", req.body.data);
})
app.listen(4589, () => console.log("start"));
Next, I send json from the main application to get the converted excel file.
Part from controller С#
public async Task<FileContentResult> GetExcelFile([FromBody] List<GoodsModel> dataList)
{
SideServices sideServices = new(Db, Logger);
List<object> responseDataList = new List<object> { };
object fields = new { codeElem = "Код элемента", shortName = "Наименование", unit = "система измерения", baseNds = "НДС",
sellPrice = "Цена штю", unitWeight = "вес", sumUtd = "Всего, руб", priceUtd = "Цена парйс УТД", baseSale = "Базовая скидка",
remainder = "Cвободный остаток", priceEutd = "Цена eUTD", sumEutd = "Сумма eUTD"};
foreach (GoodsModel item in dataList)
{
responseDataList.Add(new {
codeElem = item.CodeElem,
shortName = item.ShortName,
unit = item.Unit,
baseNds = item.BaseNds,
sellPrice = item.SellPrice,
unitWeight = item.UnitWeight,
sumUtd = item.Sum,
priceUtd = item.PriceUtd,
baseSale = item.BaseSale,
remainder = item.Remainder,
priceEutd = item.PriceEutd,
sumEutd = item.SumEutd
});
}
ExcelImportModel importModel = new ExcelImportModel {
Fields = fields,
Styles = new { },
NameFile = $"Счёт на оплату oт " + SideServices.CurrentDate.ToString(),
DataList = responseDataList.ToArray()
};
Tuple<bool, string, byte[]> resultImport = await sideServices.ToExcelAsync(importModel);
if (resultImport.Item1 == false)
{
string contentType = "application/vnd.ms-excel";
string nameFile = $"Счёт на оплату oт " + SideServices.CurrentDate.ToString();
return File(resultImport.Item3, contentType, nameFile);
}
else
{
return File(new byte[] {1,2,3 }, string.Empty);
}
}
Next method ToExcelAsync():
internal async Task<Tuple<bool, string, byte[]>> ToExcelAsync(ExcelImportModel excelImport)
{
if (excelImport.DataList.Length == 0) return Tuple.Create(true, "Length data is null", new byte[] { 1, 2, 3 });
FileSettings fileSettings = new();
string settingString = await fileSettings.ReadSwitchAsync(TypeDo.settings);
SettingsModel settings = JsonSerializer.Deserialize<SettingsModel>(settingString);
RestClient restClient = new("http://127.0.0.1:4589?" + "token=" + settings.SiteSetModel.APITOKEN);
RestRequest restRequest = new(Method.POST);
restRequest.AddJsonBody(excelImport, "application/json");
IRestResponse response = await restClient.ExecuteAsync(restRequest);
if (response.StatusCode == HttpStatusCode.OK)
{
return Tuple.Create(false, string.Empty, Encoding.UTF8.GetBytes(response.Content));
}
else return Tuple.Create(true, response.ErrorMessage, new byte[] { 1, 2, 3 });
}
Further, on the client side, I get an array of bytes of the generated file.
export default function ExcelConvert(){
const [dataConvert, setDataConvert] = useState([]);
const [errorModal, setErrorModal] = useState({isVisible: false, errorText: ""});
const [appendData, setAppendData] = useState({url: ""});
const ref = useRef(null);
const selector = useSelector(state => state.mainElements);
useEffect(()=>{
const responseArray = [];
for (let i = 0; i < selector.length; i++) {
const element = selector[i];
const newObj = {
codeElem: element.codeElem,
shortName: element.shortName,
countUnit: element.countUnit,
baseUnit: element.baseUnit,
weight: element.unitWeight,
sellPrice: element.sellPrice,
priceUtd: element.sellPrice,
sumUtd: element.sumPrice,
priceEutd: element.priceEUTD,
sumEutd: element.sumEUTD,
baseSale: element.discountItem,
remainder: element.amountUnits
}
responseArray.push(newObj);
}
setDataConvert(responseArray)
}, [selector]);
const handlerClick = () => {
if(dataConvert.length <= 0) return undefined;
const userToken = sessionStorage.getItem("t");
fetch(`${baseurl}/connect/account/excel`, {
method: "POST",
headers: {"Authorization": `Bearer ${userToken}`, "Content-Type": "application/json"},
body: JSON.stringify(dataConvert)
}).then((response) => {
const status = response.status;
if(status === 200) return response.blob();
if(status === 401) deleteAuthData();
if(status >= 400 && status !== 401) setErrorModal({isVisible: true, errorText: "Невозможно загрузить файл!"})
}).then((result) => {
setAppendData({url: window.URL.createObjectURL([result])});
}).catch(e => setErrorModal({isVisible: true, errorText: e}));
}
return <>
<button onClick={handlerClick}>скачать Excel</button>
{appendData.url ? <a style={{display: "block"}} download={"qw.xlsx"} ref={ref} href={appendData.url}>test</a> : <></>}
</>
}
In the first visualization of the code, I added a function that saves the generated excel file;
This file is valid and opens normally.
But the file that I upload on the client side, the file does not open and indicates that the file is not valid and has the wrong format.
Help me solve this problem, what am I doing wrong?

VOID code behind working. String return using Ajax not working. (Checking PayPal details)

I'm trying to convert a void code behind call to PayPal which checks a users PayPal details, to an Ajax call to work in the background.
I'm struggling to
Turn from Void to a String to return the value for Ajax
When I do use my method of a string, it just times out - even if I set timeout to a ridiculously high number. Then it fails and just comes back as undefined.
Working code behind void code:
public async void checkAccAsync()
{
userManager um = new userManager();
var userID = HttpContext.Current.User.Identity.GetUserId();
um.Get(userID);
var subid = um.ppID.Trim();
var token = getToken();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.paypal.com/v1/billing/subscriptions/" + subid))
{
var id = "";
var nextPayment = "";
var status = "";
var payerEmail = "";
var currency = "";
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var response = await httpClient.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
var obj2 = JsonConvert.DeserializeObject<dynamic>(res);
id = obj2.id;
nextPayment = obj2.billing_info.next_billing_time;
if (nextPayment == null)
{
nextPayment = obj2.billing_info.last_payment.time;
var nextPayment2 = Convert.ToDateTime(nextPayment);
nextPayment2.AddMonths(1);
nextPayment = nextPayment2.ToString();
}
status = obj2.status;
status = status.ToLower();
status = FirstLetterToUpper(status);
payerEmail = obj2.subscriber.email_address;
currency = obj2.shipping_amount.currency_code;
um.updatePaypal_noIPN(id, status, "Regular", nextPayment, payerEmail, currency);
}
}
}
Ajax call with String (ideal method), which isn't working.
[WebMethod]
public async System.Threading.Tasks.Task<string> CheckAccAsync()
{
userManager um = new userManager();
var userID = HttpContext.Current.User.Identity.GetUserId();
um.Get(userID);
var subid = um.ppID.Trim();
var token = getToken();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.paypal.com/v1/billing/subscriptions/" + subid))
{
var id = "";
var nextPayment = "";
var status = "";
var payerEmail = "";
var currency = "";
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var response = await httpClient.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
var obj2 = JsonConvert.DeserializeObject<dynamic>(res);
id = obj2.id;
nextPayment = obj2.billing_info.next_billing_time;
if (nextPayment == null)
{
nextPayment = obj2.billing_info.last_payment.time;
var nextPayment2 = Convert.ToDateTime(nextPayment);
nextPayment2.AddMonths(1);
nextPayment = nextPayment2.ToString();
}
status = obj2.status;
status = status.ToLower();
status = FirstLetterToUpper(status);
payerEmail = obj2.subscriber.email_address;
currency = obj2.shipping_amount.currency_code;
um.updatePaypal_noIPN(id, status, "Regular", nextPayment, payerEmail, currency);
return status + ", "+payerEmail+", ";
}
}
}
And the jQuery which calls it:
$( document ).ready(function() {
$.ajax({
type: "POST",
url: '/WebServices/checkPayPal.asmx/CheckAccAsync',
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 150000
});
});
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(data, status) { // error 2
alert(data.error)
};
Why isn't my Ajax string method not working?

Instagram Api (https://api.instagram.com/oauth/access_token" , "post" , parameters) returns 400 Bad Request

I am developing an app using instagram api to bring feed to my website. I have following code but when i try to access the access_token using the code provided by Instagram it's giving me `400 Bad request error. I would be much obliged if someone could help me to overcome this problem. Many Thanks
string code="";
public ActionResult Index()
{
if (!String.IsNullOrEmpty(Request["code"]))
{
code = Request["code"].ToString();
GetDataInstagramToken();
}
return View();
}
public ActionResult Instagram()
{
var client_id = ConfigurationManager.AppSettings["instagram.clientid"].ToString();
var redirect_uri = ConfigurationManager.AppSettings["instagram.redirecturi"].ToString();
string url = "https://api.instagram.com/oauth/authorize/?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=code";
Response.Redirect(url);
return View();
}
public void GetDataInstagramToken()
{
var json = "";
var page = HttpContext.CurrentHandler as Page;
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());
parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
int id = (int)jsResult["user"]["id"];
//This code register id and access token to get on client side
page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken", "<script> var instagramaccessid=\"" + #"" + id + "" + "\"; var instagramaccesstoken=\"" + #"" + accessToken + "" + "\";</script>");
}
catch (Exception ex)
{
throw;
}
}
I am getting exception at
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
In this line
client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
You don't send any value to Instagram. If you check your parameter you can see your key but you cant see any value.
Try this:
public async void GetTokenFromCode()
{
var values = new Dictionary<string, string> {
{ "client_id","Your ChatId" },
{ "client_secret", "Your Client Secret" },
{ "grant_type", "authorization_code" },
{ "redirect_uri", "Your Redirect url"},
{ "code", "code" } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.instagram.com/oauth/access_token", content);
var responseString = await response.Content.ReadAsStringAsync();
}

Asp.net WebApi method instead of AngularJs Service

I have written Angularjs service as shown below.It retrieves data from the 3rd party service.It's working fine.
Now I have a requirement to write a WebApi method for the same.The reason for that is, we can consume that service from various types of applications.i.e. desktop, web and mobile.How can I implement such a service?
AngulaJS service:
(function () {
appModule.service('getPropertyDetailsByUsingApiService', ['$http', function ($http) {
this.propertyDetails = function (token, number, street, county, zip) {
var endpointUrl = 'http://myaddress.com/api/AddressMatcher?Token=';
var url = endpointUrl + token + '&Number=' + number + '&Street=' + street + '&County=' + county + '&Zip=' + zip;
return $http.get(url).then(function (data) {
var result = data;
if (result.data[0].Status == 'OK') {
return $http.get(endpointUrl + token + '&Apn=' + result.data[0].Result[0].APN + '&County=' + county)
.then(function (finalData) {
return finalData;
});
} else {
return null;
}
});
};
}
]);
})();
WebApi method :
[HttpGet]
public async Task<MyModelDto> GetPropertyDetailsByUsingApiService()
{
//I would like to have a help here to implement it
return result;
}
I guess you are looking for HttpClient.GetAsync.
For example,
var response = await client.GetAsync("http://...");
if (response.IsSuccessStatusCode) {
...
}
Use this,
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiDetails.BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync(apiDetails.RequestUrl, obj).Result;
}

How to mock a OWIN Testserver with RestSharp?

I'm using OWIN with WebAPI integration as WebApp. Future plan is to use OWIN self-hosting which is working fine but the OWIN testserver implementation is not working together with RestSharp:
Sample without RestSharp:
https://blogs.msdn.microsoft.com/webdev/2013/11/26/unit-testing-owin-applications-using-testserver/
First attempt is to use a mock class derived from RestClient class:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
var response = TestServer.HttpClient.GetAsync(request.Resource).Result;
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}
Unfortunatly I stuck with Post events, which needs html body from restResponse.
Has anybody done something similar.
BTW: I can also use OWIN unit tests with self-hosting OWIN, but this will not work on Teamcity automatic builds.
I changed the mock rest Client to work with Post/Put/Delete methods too. It is not 100% complete (missing auth, Cookies, files etc.), but in my case it is sufficient:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
HttpResponseMessage response = null;
Parameter body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
HttpContent content;
if (body != null)
{
object val = body.Value;
byte[] requestBodyBytes;
string requestBody;
if (val is byte[])
{
requestBodyBytes = (byte[]) val;
content = new ByteArrayContent(requestBodyBytes);
}
else
{
requestBody = Convert.ToString(body.Value);
content = new StringContent(requestBody);
}
}
else
content = new StringContent("");
string urladd = "";
IEnumerable<string> #params = from p in request.Parameters
where p.Type == ParameterType.GetOrPost && p.Value != null
select p.Name + "=" + p.Value;
if(!#params.IsNullOrEmpty())
urladd = "?" + String.Join("&", #params);
IEnumerable<HttpHeader> headers = from p in request.Parameters
where p.Type == ParameterType.HttpHeader
select new HttpHeader
{
Name = p.Name,
Value = Convert.ToString(p.Value)
};
foreach (HttpHeader header in headers)
{
content.Headers.Add(header.Name, header.Value);
}
content.Headers.ContentType.MediaType = "application/json";
switch (request.Method)
{
case Method.GET:
response = TestServer.HttpClient.GetAsync(request.Resource + urladd).Result;
break;
case Method.DELETE:
response = TestServer.HttpClient.DeleteAsync(request.Resource + urladd).Result;
break;
case Method.POST:
response = TestServer.HttpClient.PostAsync(request.Resource + urladd, content).Result;
break;
case Method.PUT:
response = TestServer.HttpClient.PutAsync(request.Resource + urladd, content).Result;
break;
default:
return null;
}
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}

Categories